import { useEffect, useState } from "react";
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 { AddDomain } from "../partials/Admin/AddDomain";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";

export default function Domains() {
  const { openModal } = useModalStore();
  const [domainsInfo, setDomainsInfo] = useState({ page: 1, page_size: 10 });
  const [domainsTableData, setDomainsTableData] = useState([]);

  const { data: domainsData, refetch } = useApiRequest({
    api: "/core/domain/",
    method: "get",
    params: domainsInfo,
    queryKey: ["domains", domainsInfo],
  });

  useEffect(() => {
    if (domainsData?.results) {
      const formattedData = domainsData.results.map((item: any, i: number) => {
        return [
          domainsInfo.page === 1
            ? i + 1
            : i + domainsInfo.page_size * (domainsInfo.page - 1) + 1,
          item?.fa_name,
          item?.code,
          item?.name,
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش حوزه",
                    content: <AddDomain item={item} getData={refetch} />,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              api={`core/domain/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setDomainsTableData(formattedData);
    }
  }, [domainsData, domainsInfo]);

  return (
    <Grid container column>
      <Grid container className="items-center gap-2">
        <Button
          size="small"
          variant="submit"
          onClick={() => {
            openModal({
              title: "ایجاد حوزه",
              content: <AddDomain getData={refetch} />,
            });
          }}
        >
          ایجاد حوزه
        </Button>
      </Grid>
      <Table
        className="mt-2"
        onChange={setDomainsInfo}
        count={domainsData?.count || 10}
        isPaginated
        title="حوزه ها"
        columns={["ردیف", "نام حوزه", "کد حوزه", "نام انگلیسی", "عملیات"]}
        rows={domainsTableData}
      />
    </Grid>
  );
}
