import { useEffect, useState } from "react";
import { useApiRequest } from "../utils/useApiRequest";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { useNavigate, useParams } from "@tanstack/react-router";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { useModalStore } from "../context/zustand-store/appStore";
import { ChildOrganizations } from "../partials/cooperatives/ChildOrganizations";
import { COOPERATIVE_LIST } from "../routes/paths";
import { TableButton } from "../components/TableButton/TableButton";
import { CooperativesDashboardDetails } from "../partials/cooperatives/CooperativesDashboardDetails";
import { AddActivityType } from "../partials/cooperatives/AddActivityType";
import ShowMoreInfo from "../components/ShowMoreInfo/ShowMoreInfo";
import ShowStringList from "../components/ShowStringList/ShowStringList";

export default function Cooperatives() {
  const { openModal } = useModalStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [cooperativesTableData, setCooperativesTableData] = useState([]);
  const { id, name } = useParams({ strict: false });
  const navigate = useNavigate();

  const { data: cooperativesData, refetch } = useApiRequest({
    api: `herd/web/api/v1/rancher_org_link/org_linked_rancher_list${
      id ? `?org_id=${id}` : ""
    }`,
    method: "get",
    params: {
      ...pagesInfo,
    },
    queryKey: [id ? "unioncooperatives" : "cooperatives", pagesInfo],
  });

  const { data: cooperativesDashboardData } = useApiRequest({
    api: `herd/web/api/v1/rancher_org_link/${id}/org_ranchers_quota_dashboard/`,
    method: "get",
    queryKey: [id ? "unionCooperativeDashboard" : "cooperativeDashboard"],
    enabled: !!id,
  });

  useEffect(() => {
    if (cooperativesData?.results) {
      const formattedData = cooperativesData.results.map(
        (item: any, i: number) => {
          return [
            pagesInfo.page === 1
              ? i + 1
              : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
            item?.name || "-",
            item?.province || "-",
            item?.city || "-",
            item?.rancher_count || 0,
            item?.herd_count || 0,
            item?.livestock_count || 0,
            item?.org_service_area?.length ? (
              <ShowMoreInfo key={i} title="محدوده فعالیت">
                <Grid
                  container
                  column
                  className="gap-2 p-2 justify-start items-start w-full"
                >
                  <ShowStringList
                    showSearch={false}
                    strings={item.org_service_area.map(
                      (city: any) => city.name
                    )}
                  />
                </Grid>
              </ShowMoreInfo>
            ) : (
              "-"
            ),
            item?.org_purchase_policy === "INTERNAL_ONLY"
              ? "بر اساس تعاونی"
              : item?.org_purchase_policy === "CROSS_COOP"
              ? "برای کل استان"
              : "-",
            <Popover key={i}>
              <Tooltip title="دامداران تعاونی" position="right">
                <Button
                  variant="view"
                  page="cooperative_ranchers"
                  access="Show-Cooperative-Ranchers"
                  onClick={() => {
                    const path =
                      COOPERATIVE_LIST +
                      "/ranchers/" +
                      item?.id +
                      "/" +
                      item?.name;
                    navigate({ to: path });
                  }}
                />
              </Tooltip>
              <Tooltip title="تعریف نوع فعالیت" position="right">
                <Button
                  variant="set"
                  page="cooperatives"
                  access="Set-Cooperative-Activity-Type"
                  onClick={() => {
                    openModal({
                      title: `تعریف نوع فعالیت ${item?.name || ""}`,
                      content: (
                        <AddActivityType getData={refetch} item={item} />
                      ),
                    });
                  }}
                />
              </Tooltip>
            </Popover>,

            <Tooltip title="زیرمجموعه ها" position="right">
              <Button
                variant="detail"
                page="cooperatives"
                access="Show-Child-Organizations"
                onClick={() => {
                  openModal({
                    title: `زیرمجموعه های ${item?.name || ""}`,
                    content: (
                      <ChildOrganizations
                        orgId={item?.id}
                        orgName={item?.name || ""}
                      />
                    ),
                    isFullSize: true,
                  });
                }}
              />
            </Tooltip>,
          ];
        }
      );
      setCooperativesTableData(formattedData);
    }
  }, [cooperativesData, pagesInfo, openModal, navigate, refetch]);

  return (
    <Grid container column className="gap-4 mt-2">
      {id && (
        <Grid isDashboard>
          <Table
            isDashboard
            title="خلاصه اطلاعات"
            noPagination
            noSearch
            columns={[
              "تعداد کل سهمیه ها",
              "مجموع وزن سهمیه ها (کیلوگرم)",
              "مجموع وزن توزیع شده (کیلوگرم)",
              "مجموع وزن باقیمانده (کیلوگرم)",
              "مجموع وزن فروش رفته (کیلوگرم)",
              "مجموع وزن ورود به انبار (کیلوگرم)",
              "جزئیات",
            ]}
            rows={[
              [
                cooperativesDashboardData?.quotas_summary?.total_quotas?.toLocaleString() ||
                  0,
                cooperativesDashboardData?.quotas_summary?.total_amount?.toLocaleString() ||
                  0,
                cooperativesDashboardData?.quotas_summary?.total_distributed?.toLocaleString() ||
                  0,
                cooperativesDashboardData?.quotas_summary?.remaining_amount?.toLocaleString() ||
                  0,
                cooperativesDashboardData?.quotas_summary?.sold_amount?.toLocaleString() ||
                  0,
                cooperativesDashboardData?.quotas_summary?.inventory_received?.toLocaleString() ||
                  0,
                <TableButton
                  size="small"
                  key="details"
                  onClick={() => {
                    openModal({
                      title: "جزئیات",
                      content: <CooperativesDashboardDetails orgId={id} />,
                      isFullSize: true,
                    });
                  }}
                >
                  جزئیات
                </TableButton>,
              ],
            ]}
          />
        </Grid>
      )}

      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={cooperativesData?.count || 10}
        isPaginated
        title={id ? `تعاونی های ${name}` : "تعاونی ها"}
        columns={[
          "ردیف",
          "نام",
          "استان",
          "شهر",
          "تعداد دامدار",
          "تعداد گله",
          "تعداد دام",
          "محدوده فعالیت",
          "محدودیت دریافت نهاده",
          "عملیات",
        ]}
        rows={cooperativesTableData}
      />
    </Grid>
  );
}
