import BreadCrumbs from "@/components/BreadCrumbs";
import DesaSetting from "@/components/DesaSetting";
import KategoriPelayananSurat from "@/components/KategoriPelayananSurat";
import KategoriPengaduan from "@/components/KategoriPengaduan";
import ProfileUser from "@/components/ProfileUser";
import UserRoleSetting from "@/components/UserRoleSetting";
import UserSetting from "@/components/UserSetting";
import apiFetch from "@/lib/apiFetch";
import { Card, Container, Grid, NavLink } from "@mantine/core";
import {
  IconBuildingBank,
  IconCategory2,
  IconMailSpark,
  IconUserCog,
  IconUserScreen,
  IconUsersGroup,
} from "@tabler/icons-react";
import type { JsonValue } from "generated/prisma/runtime/library";
import _ from "lodash";
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";

export default function DetailSettingPage() {
  const { search } = useLocation();
  const query = new URLSearchParams(search);
  const type = query.get("type");
  const navigate = useNavigate();
  const [permissions, setPermissions] = useState<JsonValue[]>([]);
  const dataMenu = [
    { title: "Dashboard", link: "/scr/dashboard/dashboard-home", active: false },
    { title: "Setting", link: "#", active: false },
    { title: type == "cat-pengaduan" ? "Kategori Pengaduan" : type == "cat-pelayanan" ? "Kategori Pelayanan Surat" : type ? _.upperFirst(type) : "Profile", link: "#", active: true },
  ];

  useEffect(() => {
    async function fetchPermissions() {
      const { data } = await apiFetch.api.user.find.get();
      if (Array.isArray(data?.permissions)) {
        const onlySetting = data.permissions.filter((p: any) =>
          p.startsWith("setting"),
        );
        setPermissions(onlySetting);
      } else {
        setPermissions([]);
      }
    }
    fetchPermissions();
  }, []);

  const navItems = [
    {
      key: "setting.profile",
      path: "profile",
      icon: <IconUserCog size={20} />,
      label: "Profile",
      description: "Manage profile settings",
    },
    {
      key: "setting.user",
      path: "user",
      icon: <IconUsersGroup size={20} />,
      label: "User",
      description: "Manage user accounts",
    },
    {
      key: "setting.user_role",
      path: "role",
      icon: <IconUserScreen size={20} />,
      label: "Role",
      description: "Manage user roles",
    },
    {
      key: "setting.kategori_pengaduan",
      path: "cat-pengaduan",
      icon: <IconCategory2 size={20} />,
      label: "Kategori Pengaduan",
      description: "Manage complaint categories",
    },
    {
      key: "setting.kategori_pelayanan",
      path: "cat-pelayanan",
      icon: <IconMailSpark size={20} />,
      label: "Kategori Pelayanan Surat",
      description: "Manage letter service categories",
    },
    {
      key: "setting.desa",
      path: "desa",
      icon: <IconBuildingBank size={20} />,
      label: "Desa",
      description: "Manage desa information",
    },
  ];

  return (
    <Container size="xl" py="xl" w={"100%"}>
      <Grid>
        <Grid.Col span={12}>
          <BreadCrumbs dataLink={dataMenu} back />
        </Grid.Col>
        <Grid.Col span={3}>
          <Card
            radius="md"
            p="lg"
            withBorder
            style={{
              background:
                "linear-gradient(145deg, rgba(25,25,25,0.95), rgba(45,45,45,0.85))",
              borderColor: "rgba(100,100,100,0.2)",
              boxShadow: "0 0 20px rgba(0,255,200,0.08)",
            }}
          >
            {navItems
              .filter((item) => permissions.includes(item.key))
              .map((item) => (
                <NavLink
                  key={item.key}
                  onClick={()=>{navigate("?type=" + item.path)}}
                  label={item.label}
                  leftSection={item.icon}
                  active={
                    type === item.path || (!type && item.path === "profile")
                  }
                />
              ))}
          </Card>
        </Grid.Col>
        <Grid.Col span={9}>
          <Card
            radius="md"
            p="lg"
            withBorder
            style={{
              background:
                "linear-gradient(145deg, rgba(25,25,25,0.95), rgba(45,45,45,0.85))",
              borderColor: "rgba(100,100,100,0.2)",
              boxShadow: "0 0 20px rgba(0,255,200,0.08)",
            }}
          >
            {type === "cat-pengaduan" ? (
              <KategoriPengaduan
                permissions={permissions.filter(
                  (p) =>
                    typeof p === "string" &&
                    p.startsWith("setting.kategori_pengaduan"),
                )}
              />
            ) : type === "cat-pelayanan" ? (
              <KategoriPelayananSurat
                permissions={permissions.filter(
                  (p) =>
                    typeof p === "string" &&
                    p.startsWith("setting.kategori_pelayanan"),
                )}
              />
            ) : type === "desa" ? (
              <DesaSetting
                permissions={permissions.filter(
                  (p) => typeof p === "string" && p.startsWith("setting.desa"),
                )}
              />
            ) : type === "user" ? (
              <UserSetting
                permissions={permissions.filter(
                  (p) => typeof p === "string" && p.startsWith("setting.user."),
                )}
              />
            ) : type === "role" ? (
              <UserRoleSetting
                permissions={permissions.filter(
                  (p) =>
                    typeof p === "string" && p.startsWith("setting.user_role"),
                )}
              />
            ) : (
              <ProfileUser
                permissions={permissions.filter(
                  (p) =>
                    typeof p === "string" && p.startsWith("setting.profile"),
                )}
              />
            )}
          </Card>
        </Grid.Col>
      </Grid>
    </Container>
  );
}
