import { useEffect, useState } from "react";
import { useApiRequest } from "../utils/useApiRequest";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { COOPERATIVE_LIST } from "../routes/paths";
import { useNavigate } from "@tanstack/react-router";

export default function Unions() {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [unionsTableData, setUnionsTableData] = useState([]);
  const navigate = useNavigate();

  const { data: unionsData } = useApiRequest({
    api: "/auth/api/v1/organization/get_union_orgs/",
    method: "get",
    params: {
      ...pagesInfo,
    },
    queryKey: ["unions", pagesInfo],
  });

  useEffect(() => {
    if (unionsData?.results) {
      const formattedData = unionsData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.name || "-",
          item?.type?.name || "-",
          item?.province?.name || "-",
          item?.city?.name || "-",
          item?.parent_organization?.name || "-",
          item?.national_unique_id || "-",
          item?.address || "-",
          <Popover key={i}>
            <Tooltip title="نمایش تعاونی ها" position="right">
              <Button
                variant="detail"
                page={"union_cooperatives"}
                access="Show-Union-Cooperatives"
                onClick={() => {
                  const path =
                    COOPERATIVE_LIST + "/" + item?.id + "/" + item?.name;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
          </Popover>,
        ];
      });
      setUnionsTableData(formattedData);
    }
  }, [unionsData, pagesInfo]);

  return (
    <Grid container column>
      <Table
        className="mt-2"
        onChange={setPagesInfo}
        count={unionsData?.count || 10}
        isPaginated
        title="اتحادیه ها"
        columns={[
          "ردیف",
          "نام",
          "نوع سازمان",
          "استان",
          "شهر",
          "سازمان والد",
          "شناسه کشوری",
          "آدرس",
          "عملیات",
        ]}
        rows={unionsTableData}
      />
    </Grid>
  );
}
