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";

export default function UnusedAccess() {
  const { openModal } = useModalStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

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

  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})`,
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش دسترسی",
                    content: <AddAccess item={item} getData={refetch} />,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              api={`auth/api/v1/permission/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setPagesTableData(formattedData);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      <Table
        className="mt-2"
        onChange={setPagesInfo}
        count={pagesData?.count || 10}
        isPaginated
        title="دسترسی های غیر فعال"
        columns={["ردیف", "دسترسی", "توضیحات", "صفحه", "عملیات"]}
        rows={pagesTableData}
      />
    </Grid>
  );
}
