import Table from "../components/Table/Table";
import { Grid } from "../components/Grid/Grid";
import { useApiRequest } from "../utils/useApiRequest";
import { useEffect, useState } from "react";
import { getFaPermissions } from "../utils/getFaPermissions";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import {
  useDrawerStore,
  useModalStore,
} from "../context/zustand-store/appStore";
import { EditAccess } from "../partials/management/EditAccess";
import { AddUser } from "../partials/management/AddUser";
import ShowStringList from "../components/ShowStringList/ShowStringList";
import ShowMoreInfo from "../components/ShowMoreInfo/ShowMoreInfo";
import AutoComplete from "../components/AutoComplete/AutoComplete";
import { useUserProfileStore } from "../context/zustand-store/userStore";

type PermissionType = {
  page_name: string;
};

export default function Users() {
  const { openModal } = useModalStore();
  const { openDrawer } = useDrawerStore();
  const [selectedRolesKeys, setSelectedRolesKeys] = useState<
    (string | number)[]
  >([]);
  const { profile } = useUserProfileStore();
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [tableData, setTableData] = useState([]);

  const { data: apiData, refetch } = useApiRequest({
    api: `/auth/api/v1/user-relations/?role=${selectedRolesKeys[0] || ""}`,
    method: "get",
    params: params,
    queryKey: ["users", params, selectedRolesKeys],
  });

  const { data: rolesData } = useApiRequest({
    api: "/auth/api/v1/role/",
    method: "get",
    params: { page: 1, page_size: 1000 },
    queryKey: ["roles"],
  });

  const formattedRolesData = [
    {
      key: "",
      value: "کل نقش ها",
    },
    ...(rolesData?.results
      ?.filter((role: any) => {
        if (profile?.role?.type?.key !== "ADM") {
          return role.type?.key !== "ADM";
        }
        return true;
      })
      ?.map((role: any) => ({
        key: role.id,
        value: role.role_name,
      })) || []),
  ];

  useEffect(() => {
    if (apiData?.results) {
      const formattedData = apiData.results.map((item: any, i: number) => {
        const permissionLength = item?.permissions?.length;
        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.user?.username,
          item?.user?.first_name,
          item?.user?.last_name,
          item?.organization?.name,
          item?.role?.role_name,
          item?.user?.mobile,
          item?.user?.national_code,
          item?.user?.province_name
            ? `${item?.user?.province_name} (${item?.user?.city_name})`
            : "-",
          item?.user?.address || "-",
          item?.user?.ownership === "L" ? "حقوقی" : "حقیقی",
          item?.user?.unit_name || "-",
          item?.user?.unit_national_id || "-",
          item?.user?.is_active ? "فعال" : "غیر فعال",
          <ShowMoreInfo
            key={i}
            title="دسترسی ها"
            disabled={!permissionLength}
            counter={permissionLength}
          >
            <ShowStringList
              strings={item?.permissions?.map((option: PermissionType) =>
                getFaPermissions(option?.page_name)
              )}
            />
          </ShowMoreInfo>,
          <Popover key={i}>
            <Tooltip title="ویرایش پروفایل کاربر" position="right">
              <Button
                page="users"
                access="Update-User-Profile"
                variant="edit"
                onClick={() => {
                  openDrawer({
                    title: "ویرایش پروفایل کاربر",
                    content: <AddUser getData={refetch} item={item} />,
                  });
                }}
              />
            </Tooltip>
            <Tooltip title="ویرایش دسترسی کاربر" position="right">
              <Button
                page="users"
                access="Update-User-Access"
                variant="secondary-edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش دسترسی کاربر",
                    content: <EditAccess getData={refetch} item={item} />,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="users"
              access="Delete-User"
              title="از حذف کاربر اطمینان دارید؟"
              api={`/auth/api/v1/user/${item?.user?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTableData(formattedData);
    }
  }, [apiData, params]);

  return (
    <>
      <Grid container className="items-center gap-2">
        <Grid>
          <Button
            size="small"
            page="users"
            access="Create-User"
            variant="submit"
            onClick={() =>
              openDrawer({
                title: "ایجاد کاربر",
                content: <AddUser getData={refetch} />,
                isOpen: true,
                direction: "left",
              })
            }
          >
            ایجاد کاربر
          </Button>
        </Grid>
        <Grid>
          <AutoComplete
            inPage
            size="small"
            data={formattedRolesData}
            selectedKeys={selectedRolesKeys}
            onChange={setSelectedRolesKeys}
            title="فیلتر نقش"
          />
        </Grid>
      </Grid>
      <Grid className="w-full">
        <Table
          className="mt-2"
          onChange={setParams}
          excelInfo={{
            link: "auth/excel/user_relations_excel/",
          }}
          title="کاربران"
          isPaginated
          count={apiData?.count || 10}
          columns={[
            "ردیف",
            "نام کاربری",
            "نام",
            "نام خانوادگی",
            "سازمان",
            "نقش",
            "موبایل",
            "کد ملی",
            "استان/شهر",
            "آدرس",
            "مالکیت",
            "نام واحد",
            "شناسه ملی واحد",
            "وضعیت",
            "دسترسی ها",
            "عملیات",
          ]}
          rows={tableData}
        />
      </Grid>
    </>
  );
}
