import { useEffect, useState } from "react";
import { useModalStore } from "../context/zustand-store/appStore";
import { useApiRequest } from "../utils/useApiRequest";
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 { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { AddRole } from "../partials/management/AddRole";
import { getFaPermissions } from "../utils/getFaPermissions";
import ShowStringList from "../components/ShowStringList/ShowStringList";
import ShowMoreInfo from "../components/ShowMoreInfo/ShowMoreInfo";
import Typography from "../components/Typography/Typography";

export default function Roles() {
  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/role/",
    method: "get",
    params: pagesInfo,
    queryKey: ["roles", pagesInfo],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        const accessList = Object.values(
          item?.permissions.reduce((acc: any, item: any) => {
            if (!acc[item.page]) {
              acc[item.page] = {
                page: item.page,
                names: [],
                descriptions: [],
              };
            }
            acc[item.page].names.push(item.name);
            acc[item.page].descriptions.push(item.description);
            return acc;
          }, {})
        );

        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.role_name,
          item?.parent_role?.name || "-",
          item?.type?.name,
          item?.type?.key || "-",
          item?.description,
          <ShowMoreInfo
            key={i}
            title="دسترسی ها"
            counter={[accessList?.length.toString()]}
            disabled={!accessList?.length}
          >
            <Grid
              container
              column
              className="gap-2 p-2 justify-start items-start"
            >
              {accessList?.map((opt: any) => (
                <Grid key={i} container column className="gap-2">
                  <Grid>
                    <Typography variant="subtitle2" sign="arrow">
                      {getFaPermissions(opt.page)}
                    </Typography>
                  </Grid>
                  <Grid>
                    <ShowStringList
                      strings={opt.descriptions}
                      showSearch={false}
                    />
                  </Grid>
                </Grid>
              ))}
            </Grid>{" "}
          </ShowMoreInfo>,
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                page="roles_management"
                access="Edit-Role"
                onClick={() => {
                  openModal({
                    title: "ویرایش نقش",
                    content: <AddRole item={item} getData={refetch} />,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="roles_management"
              access="Delete-Role"
              api={`auth/api/v1/role/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      <Grid>
        <Button
          size="small"
          page="roles_management"
          access="Post-Role"
          variant="submit"
          onClick={() => {
            openModal({
              title: "ایجاد نقش",
              content: <AddRole getData={refetch} />,
            });
          }}
        >
          ایجاد نقش
        </Button>
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        title="لیست نقش ها"
        columns={[
          "ردیف",
          "نقش",
          "نقش والد",
          "نوع نقش",
          "کلید",
          "توضیحات",
          "دسترسی ها",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
}
