import { useEffect, useState } from "react";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { useApiRequest } from "../utils/useApiRequest";
import { Popover } from "../components/PopOver/PopOver";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import {
  useDrawerStore,
  useModalStore,
} from "../context/zustand-store/appStore";
import { LiveStockAddHerd } from "../partials/live-stock/LiveStockAddHerd";
import { useNavigate, useParams } from "@tanstack/react-router";
import { LIVESTOCKS } from "../routes/paths";
import { LiveStockAddLiveStock } from "../partials/live-stock/LiveStockAddLiveStock";
import { TableButton } from "../components/TableButton/TableButton";
import { LiveStockHerdDetails } from "../partials/live-stock/LiveStockHerdDetails";

export default function LiveStocks() {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);
  const { openModal } = useModalStore();
  const { farmid, name } = useParams({ strict: false });
  const { openDrawer } = useDrawerStore();
  const { data: pagesData, refetch } = useApiRequest({
    api: farmid
      ? `herd/web/api/v1/rancher/${farmid}/herds`
      : "/herd/web/api/v1/herd/",
    method: "get",
    params: pagesInfo,
    queryKey: ["LiveStockFarmers", pagesInfo],
  });

  const { data: DashboardData, refetch: refetchDashboard } = useApiRequest<any>(
    {
      api: farmid
        ? `/herd/web/api/v1/rancher/${farmid}/rancher_dashboard/`
        : "/herd/web/api/v1/rancher/rancher_main_dashboard/",
      queryKey: ["HerdsDashboard"],
    },
  );

  const handleUpdate = () => {
    refetch();
    refetchDashboard();
  };

  const navigate = useNavigate();

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.unit_unique_id,
          item?.name,
          item?.cooperative?.name || "-",
          item?.contractor?.name || "-",
          parseInt(item?.capacity)?.toLocaleString(),
          item?.activity === "I"
            ? "صنعتی"
            : item?.activity === "V"
              ? "روستایی"
              : item?.activity === "N"
                ? "عشایری"
                : "-",
          item?.epidemiologic,
          parseInt(item?.light_livestock_number)?.toLocaleString(),
          parseInt(item?.heavy_livestock_number)?.toLocaleString(),
          item?.province?.name,
          item?.city?.name,
          item?.operating_license_state ? "دارد" : "ندارد",
          item?.activity_state ? "فعال" : "غیر فعال",
          item?.postal || "-",
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                page="livestock_farmers"
                access="Edit-Rancher"
                onClick={() =>
                  openDrawer({
                    title: "ویرایش گله",
                    content: (
                      <LiveStockAddHerd
                        getData={handleUpdate}
                        item={item}
                        rancher={item?.rancher?.id}
                      />
                    ),
                    isOpen: true,
                    direction: "left",
                  })
                }
              />
            </Tooltip>
            <Tooltip title="ایجاد دام" position="right">
              <Button
                variant="submit"
                page="herds"
                access="Add-LiveStock"
                onClick={() =>
                  openDrawer({
                    title: "ایجاد دام",
                    content: (
                      <LiveStockAddLiveStock
                        getData={handleUpdate}
                        herdId={item?.id}
                      />
                    ),
                    isOpen: true,
                    direction: "left",
                  })
                }
              />
            </Tooltip>
            <Tooltip title="مشاهده دام ها" position="right">
              <Button
                variant="detail"
                page="herd_livestocks"
                access="Get-Herd-Livestocks"
                onClick={() => {
                  const path = LIVESTOCKS + "/" + item?.id + "/" + item?.name;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="farmer_details"
              access="Delete-Rancher-Herd"
              api={`herd/web/api/v1/herd/${item?.id}/`}
              getData={handleUpdate}
            />
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      <Grid container column isDashboard>
        <Table
          isDashboard
          noPagination
          noSearch
          title="خلاصه اطلاعات"
          columns={
            farmid
              ? [
                  "تعداد کل گله ها",
                  "تعداد دام سنگین",
                  "تعداد دام سبک",
                  "مجموع وزن خرید از سهمیه ها",
                  "تعداد دام های فعال",
                  "تعداد دام های غیرفعال",
                  "جزئیات",
                ]
              : [
                  "تعداد کل گله ها",
                  "تعداد کل دامداران",
                  "تعداد گله های صنعتی",
                  "تعداد گله های روستایی",
                  "تعداد گله های عشایری",
                  "تعداد دام سبک",
                  "تعداد دام سنگین",
                  "تعداد دامداران دارای گله",
                  "تعداد دامداران بدون گله",
                  "تعداد دامداران حقیقی",
                  "تعداد دامداران حقوقی",
                  "تعداد دامداران صنعتی",
                  "تعداد دامداران روستایی",
                  "تعداد دامداران عشایری",
                ]
          }
          rows={
            farmid
              ? [
                  [
                    DashboardData?.total_herds_count?.toLocaleString() || "0",
                    DashboardData?.total_heavy_livestock_count?.toLocaleString() ||
                      "0",
                    DashboardData?.total_light_livestock_count?.toLocaleString() ||
                      "0",
                    DashboardData?.total_purchase_weight?.toLocaleString() ||
                      "0",
                    DashboardData?.total_active_livestock_count?.toLocaleString() ||
                      "0",
                    DashboardData?.total_deactive_livestock_count?.toLocaleString() ||
                      "0",
                    <TableButton
                      size="small"
                      key={DashboardData}
                      onClick={() => {
                        openModal({
                          title: "جزئیات دامدار",
                          content: (
                            <LiveStockHerdDetails farmid={farmid} name={name} />
                          ),
                          isFullSize: true,
                        });
                      }}
                    />,
                  ],
                ]
              : [
                  [
                    DashboardData?.herd_dashboard?.total_herds_count?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_ranchers_count?.toLocaleString() ||
                      "0",
                    DashboardData?.herd_dashboard?.total_industrial_herds_count?.toLocaleString() ||
                      "0",
                    DashboardData?.herd_dashboard?.total_Village_herds_count?.toLocaleString() ||
                      "0",
                    DashboardData?.herd_dashboard?.total_nomadic_herds_count?.toLocaleString() ||
                      "0",
                    DashboardData?.herd_dashboard?.total_heavy_livestock_count?.toLocaleString() ||
                      "0",
                    DashboardData?.herd_dashboard?.total_light_livestock_count?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_with_herd?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_without_herd?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_natural_ranchers?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_legal_ranchers?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_industrial_ranchers?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_village_ranchers?.toLocaleString() ||
                      "0",
                    DashboardData?.rancher_dashboard?.total_nomadic_ranchers?.toLocaleString() ||
                      "0",
                  ],
                ]
          }
        />
      </Grid>

      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        title={name ? `گله های ${name}` : "گله ها"}
        columns={[
          "ردیف",
          "شناسه یکتا",
          "نام گله",
          "نام تعاونی",
          "نام شرکت پیمانکار",
          "ظرفیت",
          "نوع فعالیت",
          "کد اپیدمیولوژیک",
          "حجم دام سبک",
          "حجم دام سنگین",
          "استان",
          "شهر",
          "مجوز فعالیت",
          "وضعیت فعالیت",
          "کد پستی",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
}
