import { useEffect, useState } from "react";
import { getFaPermissions } from "../../utils/getFaPermissions";
import { useApiRequest } from "../../utils/useApiRequest";
import { useModalStore } from "../../context/zustand-store/appStore";
import Table from "../../components/Table/Table";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import { AddAccess } from "./AddAccess";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/solid";
import AutoComplete from "../../components/AutoComplete/AutoComplete";

export default function Access() {
  const { openModal } = useModalStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);
  const [selectedModifyKeys, setSelectedModifyKeys] = useState<
    (string | number)[]
  >([]);

  const { data: pagesData, refetch } = useApiRequest({
    api: "/auth/api/v1/permission/",
    method: "get",
    params: {
      ...pagesInfo,
      modify_state: selectedModifyKeys[0],
    },
    queryKey: ["permissions", pagesInfo, selectedModifyKeys],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const formattedData = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.name,
          item?.description,
          `${getFaPermissions(item?.page)} (${item?.page})`,
          <Grid
            key={i}
            className="flex justify-center items-center bg-gray-300/10  rounded-full"
          >
            {item?.modify_state ? (
              <CheckIcon className="w-5 h-5 text-green-500" />
            ) : (
              <XMarkIcon className="w-5 h-5 text-red-500" />
            )}
          </Grid>,
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                page="permission_control"
                access="Post-access"
                onClick={() => {
                  openModal({
                    title: "ویرایش دسترسی",
                    content: <AddAccess item={item} getData={refetch} />,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="permission_control"
              access="Post-access"
              api={`auth/api/v1/permission/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setPagesTableData(formattedData);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      <Grid container className="items-center gap-2">
        <Button
          size="small"
          variant="submit"
          page="permission_control"
          access="Post-access"
          onClick={() => {
            openModal({
              title: "ایجاد دسترسی",
              content: <AddAccess getData={refetch} />,
            });
          }}
        >
          ایجاد دسترسی
        </Button>
        <AutoComplete
          inPage
          size="small"
          data={[
            { key: "", value: "کل موارد" },
            { key: "true", value: "داخلی" },
            { key: "false", value: "خارجی" },
          ]}
          selectedKeys={selectedModifyKeys}
          onChange={(keys) => {
            setSelectedModifyKeys(keys);
            setPagesInfo((prev) => ({ ...prev, page: 1 }));
          }}
          title="فیلتر نوع دسترسی"
        />
      </Grid>
      <Grid className="w-full">
        <Table
          className="mt-2"
          onChange={setPagesInfo}
          count={pagesData?.count || 10}
          isPaginated
          title="مدیریت دسترسی ها"
          columns={[
            "ردیف",
            "دسترسی",
            "توضیحات",
            "صفحه",
            "دسترسی داخلی",
            "عملیات",
          ]}
          rows={pagesTableData}
        />
      </Grid>
    </Grid>
  );
}
