import { useEffect, useState } from "react";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { useApiRequest } from "../utils/useApiRequest";
import Button from "../components/Button/Button";
import { LiveStockAddRancher } from "../partials/live-stock/LiveStockAddRancher";
import {
  useDrawerStore,
  useModalStore,
} from "../context/zustand-store/appStore";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { LiveStockAddHerd } from "../partials/live-stock/LiveStockAddHerd";
import { LiveStockAllocateCooperative } from "../partials/live-stock/LiveStockAllocateCooperative";
import { useNavigate } from "@tanstack/react-router";
import { LIVESTOCK_FARMERS } from "../routes/paths";
import { LiveStockFarmersDashboardResponse } from "../types/LiveStockFarmers";

export default function LiveStockFarmers() {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);
  const { openDrawer } = useDrawerStore();
  const { openModal } = useModalStore();

  const { data: pagesData, refetch } = useApiRequest({
    api: "/herd/web/api/v1/rancher/",
    method: "get",
    params: pagesInfo,
    queryKey: ["LiveStockFarmers", pagesInfo],
  });

  const { data: DashboardData, refetch: refetchDashboard } =
    useApiRequest<LiveStockFarmersDashboardResponse>({
      api: `/herd/web/api/v1/rancher/rancher_main_dashboard/`,
      queryKey: ["LiveStockFarmersDashboard"],
    });

  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?.ranching_farm,
          item?.first_name,
          item?.last_name,
          item?.national_code,
          item?.mobile,
          item?.organizations
            ?.map((organization: any) => organization?.name)
            .join(", "),
          item?.activity === "V"
            ? "روستایی"
            : item?.activity === "I"
              ? "صنعتی"
              : item?.activity === "R"
                ? "عشایری"
                : "-",
          item?.province?.name || "-",
          item?.city?.name || "-",
          item?.address,
          item?.without_herd ? "بدون دام" : "دامدار عادی",
          item?.rancher_type === "N" ? "حقیقی" : "حقوقی",
          item?.union_name || "-",
          item?.union_code || "-",
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                page="livestock_farmers"
                access="Edit-Rancher"
                onClick={() =>
                  openDrawer({
                    title: "ویرایش دامدار",
                    content: (
                      <LiveStockAddRancher getData={handleUpdate} item={item} />
                    ),
                    isOpen: true,
                    direction: "left",
                  })
                }
              />
            </Tooltip>
            <Tooltip title="مشاهده گله ها" position="right">
              <Button
                variant="detail"
                page="farmer_details"
                access="See-Herds"
                onClick={() => {
                  const path =
                    LIVESTOCK_FARMERS +
                    "/" +
                    item?.id +
                    "/" +
                    item?.ranching_farm;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
            <Tooltip title="ایجاد گله" position="right">
              <Button
                variant="submit"
                page="livestock_farmers"
                access="Add-Herd"
                onClick={() =>
                  openDrawer({
                    title: "ایجاد گله",
                    content: (
                      <LiveStockAddHerd
                        getData={handleUpdate}
                        rancher={item?.id}
                      />
                    ),
                    isOpen: true,
                    direction: "left",
                  })
                }
              />
            </Tooltip>
            <Tooltip title="طرح های تشویقی" position="right">
              <Button
                variant="secondary-submit"
                page="farmer_plans"
                access="Get-Rancher-Plans"
                onClick={() => {
                  const path =
                    LIVESTOCK_FARMERS +
                    "/plans/" +
                    item.id +
                    "/" +
                    `${item?.first_name.replace(":", " ") || ""} ${item?.last_name || ""} ${item?.ranching_farm ? " (" + item?.ranching_farm + ") " : ""}`;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
            <Tooltip title="تخصیص به تعاونی" position="right">
              <Button
                variant="submit"
                page="livestock_farmers"
                access="Add-Rancher-Organization"
                onClick={() =>
                  openModal({
                    title: "تخصیص به تعاونی",
                    content: (
                      <LiveStockAllocateCooperative
                        getData={handleUpdate}
                        item={item}
                      />
                    ),
                  })
                }
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="livestock_farmers"
              access="Delete-Rancher"
              api={`herd/web/api/v1/rancher/${item?.id}/`}
              getData={handleUpdate}
            />
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData]);

  return (
    <Grid container column className="gap-4">
      <Grid container column isDashboard>
        <Table
          isDashboard
          noPagination
          noSearch
          title="خلاصه اطلاعات"
          columns={[
            "تعداد کل دامداران",
            "تعداد کل گله ها",
            "تعداد گله های صنعتی",
            "تعداد گله های روستایی",
            "تعداد گله های عشایری",
            "تعداد دام سبک",
            "تعداد دام سنگین",
            "تعداد دامداران دارای گله",
            "تعداد دامداران بدون گله",
            "تعداد دامداران حقیقی",
            "تعداد دامداران حقوقی",
            "تعداد دامداران صنعتی",
            "تعداد دامداران روستایی",
            "تعداد دامداران عشایری",
          ]}
          rows={[
            [
              DashboardData?.rancher_dashboard?.total_ranchers_count?.toLocaleString() ||
                "0",
              DashboardData?.herd_dashboard?.total_herds_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>

      <Grid>
        <Button
          size="small"
          page="livestock_farmers"
          access="Post-Farmer"
          variant="submit"
          onClick={() =>
            openDrawer({
              title: "ایجاد دامدار",
              content: <LiveStockAddRancher getData={handleUpdate} />,
              isOpen: true,
              direction: "left",
            })
          }
        >
          ایجاد دامدار
        </Button>
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        title="دامداران"
        columns={[
          "ردیف",
          "نام دامداری",
          "نام",
          "نام خانوادگی",
          "کد ملی",
          "موبایل",
          "تعاونی",
          "نوع فعالیت",
          "استان",
          "شهر",
          "آدرس",
          "وضعیت",
          "نوع دامدار",
          "نام واحد حقوقی",
          "شناسه ملی واحد حقوقی",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
}
