import { useEffect, useState } from "react";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import Table from "../../components/Table/Table";
import { useModalStore } from "../../context/zustand-store/appStore";
import { useApiRequest } from "../../utils/useApiRequest";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { Popover } from "../../components/PopOver/PopOver";
import { AddOrganizationType } from "./AddOrganizationType";
import AutoComplete from "../../components/AutoComplete/AutoComplete";

export const OrganizationsTypes = () => {
  const { openModal } = useModalStore();
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [tableData, setTableData] = useState([]);

  const [selectedFieldOfActivityKeys, setSelectedFieldOfActivityKeys] =
    useState<(string | number)[]>([]);

  const { data: apiData, refetch } = useApiRequest({
    api: selectedFieldOfActivityKeys?.length
      ? `/auth/api/v1/organization-type?org_type_field=${selectedFieldOfActivityKeys[0]}`
      : "/auth/api/v1/organization-type/",
    method: "get",
    params: params,
    queryKey: ["organizationTypes", params, selectedFieldOfActivityKeys],
  });

  const fieldOfActivityItems = [
    {
      key: "",
      value: "همه حوزه ها",
    },
    {
      key: "CO",
      value: "کشور",
    },
    {
      key: "PR",
      value: "استان",
    },
    { key: "CI", value: "شهرستان" },
  ];

  useEffect(() => {
    if (apiData?.results) {
      const formattedData = apiData.results.map((item: any, i: number) => {
        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.name,
          item?.parent?.name || "-",
          item?.org_type_field === "CO"
            ? "کشور"
            : item?.org_type_field === "PR"
            ? "استان"
            : item?.org_type_field === "CI"
            ? "شهرستان"
            : "نامشخص",
          item?.is_repeatable ? "دارد" : "ندارد",
          <Popover key={i}>
            <Tooltip title="ویرایش نهاد" position="right">
              <Button
                page="organizations"
                access="Update-Organization-Type"
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش نهاد",
                    content: (
                      <AddOrganizationType getData={refetch} item={item} />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="organizations"
              access="Delete-Organization-Type"
              title="از حذف نهاد اطمینان دارید؟"
              api={`/auth/api/v1/organization-type/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTableData(formattedData);
    }
  }, [apiData, params]);

  return (
    <>
      <Grid container className="items-center gap-2">
        <Grid>
          <Button
            size="small"
            page="organizations"
            access="Create-Organization-Type"
            variant="submit"
            onClick={() =>
              openModal({
                title: "ایجاد نهاد",
                content: <AddOrganizationType getData={refetch} />,
              })
            }
          >
            ایجاد نهاد
          </Button>
        </Grid>
        <Grid>
          <AutoComplete
            inPage
            size="small"
            data={fieldOfActivityItems}
            selectedKeys={selectedFieldOfActivityKeys}
            onChange={setSelectedFieldOfActivityKeys}
            title="فیلتر حوزه فعالیت"
          />
        </Grid>
      </Grid>
      <Grid className="w-full">
        <Table
          className="mt-2"
          onChange={setParams}
          title="نهاد"
          isPaginated
          count={apiData?.count || 10}
          columns={[
            "ردیف",
            "نام",
            "نهاد والد",
            "حوزه فعالیت نهاد",
            "قابلیت تکرار",
            "عملیات",
          ]}
          rows={tableData}
        />
      </Grid>
    </>
  );
};
