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 { LIVESTOCK_FARMERS } from "../routes/paths";
import { TableButton } from "../components/TableButton/TableButton";
import { CooperativesDashboardDetails } from "../partials/cooperatives/CooperativesDashboardDetails";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";

export default function CooperativeRanchers() {
  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: cooperativeRanchersData, refetch: cooperativeRanchersRefetch } =
    useApiRequest({
      api: `herd/web/api/v1/rancher_org_link/${id}/org_ranchers/`,
      method: "get",
      params: {
        ...pagesInfo,
      },
      queryKey: ["cooperativeRanchers", pagesInfo],
    });

  const {
    data: cooperativeRanchersDashboardData,
    refetch: cooperativeRanchersDashboardRefetch,
  } = useApiRequest({
    api: `herd/web/api/v1/rancher_org_link/${id}/org_ranchers_quota_dashboard/`,
    method: "get",
    queryKey: ["cooperativeRanchersDashboard", id],
    enabled: !!id,
  });

  const handleUpdate = () => {
    cooperativeRanchersRefetch();
    cooperativeRanchersDashboardRefetch();
  };

  useEffect(() => {
    if (cooperativeRanchersData?.results) {
      const tableData = cooperativeRanchersData.results.map(
        (item: any, i: number) => {
          return [
            pagesInfo.page === 1
              ? i + 1
              : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
            item?.ranching_farm,
            item?.rancher?.first_name,
            item?.rancher?.last_name,
            item?.rancher?.national_code,
            item?.rancher?.mobile,
            item?.rancher?.activity === "V"
              ? "روستایی"
              : item?.rancher?.activity === "I"
              ? "صنعتی"
              : item?.rancher?.activity === "R"
              ? "عشایری"
              : "-",
            item?.rancher?.province?.name || "-",
            item?.rancher?.city?.name || "-",
            item?.rancher?.address,
            item?.rancher?.without_herd ? "بدون دام" : "دامدار عادی",
            item?.rancher?.rancher_type === "N" ? "حقیقی" : "حقوقی",
            item?.rancher?.union_name || "-",
            item?.rancher?.union_code || "-",
            <Popover key={i}>
              <Tooltip title="مشاهده گله ها" position="right">
                <Button
                  variant="detail"
                  page="farmer_details"
                  access="See-Herds"
                  onClick={() => {
                    const path =
                      LIVESTOCK_FARMERS +
                      "/" +
                      item?.rancher?.id +
                      "/" +
                      item?.rancher?.ranching_farm;
                    navigate({ to: path });
                  }}
                />
              </Tooltip>
              <DeleteButtonForPopOver
                page="farmer_details"
                access="Delete-Rancher-Herd"
                api={`herd/web/api/v1/rancher_org_link/${item?.id}/`}
                getData={handleUpdate}
                tooltipText="حذف دامدار از تعاونی"
                title="از حذف دامدار از تعاونی مطمئنید؟"
              />
            </Popover>,
          ];
        }
      );
      setCooperativesTableData(tableData);
    }
  }, [cooperativeRanchersData, pagesInfo, openModal]);

  return (
    <Grid container column className="gap-4 mt-2">
      {id && (
        <Grid isDashboard>
          <Table
            isDashboard
            title="خلاصه اطلاعات"
            noPagination
            noSearch
            columns={[
              "تعداد کل سهمیه ها",
              "مجموع وزن سهمیه ها (کیلوگرم)",
              "مجموع وزن توزیع شده (کیلوگرم)",
              "مجموع وزن باقیمانده (کیلوگرم)",
              "مجموع وزن فروش رفته (کیلوگرم)",
              "مجموع وزن ورود به انبار (کیلوگرم)",
              "جزئیات",
            ]}
            rows={[
              [
                cooperativeRanchersDashboardData?.quotas_summary?.total_quotas?.toLocaleString() ||
                  0,
                cooperativeRanchersDashboardData?.quotas_summary?.total_amount?.toLocaleString() ||
                  0,
                cooperativeRanchersDashboardData?.quotas_summary?.total_distributed?.toLocaleString() ||
                  0,
                cooperativeRanchersDashboardData?.quotas_summary?.remaining_amount?.toLocaleString() ||
                  0,
                cooperativeRanchersDashboardData?.quotas_summary?.sold_amount?.toLocaleString() ||
                  0,
                cooperativeRanchersDashboardData?.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={setPagesInfo}
        count={cooperativeRanchersData?.count || 10}
        isPaginated
        title={id ? `دامداران ${name}` : "دامداران تعاونی"}
        columns={[
          "ردیف",
          "نام دامداری",
          "نام",
          "نام خانوادگی",
          "کد ملی",
          "موبایل",
          "نوع فعالیت",
          "استان",
          "شهر",
          "آدرس",
          "وضعیت",
          "نوع دامدار",
          "نام واحد حقوقی",
          "شناسه ملی واحد حقوقی",
          "عملیات",
        ]}
        rows={cooperativesTableData}
      />
    </Grid>
  );
}
