import { useEffect, useState } from "react";
import { Popover } from "../components/PopOver/PopOver";
import Button from "../components/Button/Button";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { useModalStore } from "../context/zustand-store/appStore";
import { useApiRequest } from "../utils/useApiRequest";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { LiveStockRancherAllocateIncentivePlan } from "../partials/live-stock/LiveStockRancherAllocateIncentivePlan";
import { useParams } from "@tanstack/react-router";

export default function RancherPlans() {
  const { openModal } = useModalStore();
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [tableData, setTableData] = useState([]);
  const { farmid, name } = useParams({ strict: false });

  const { data: apiData, refetch } = useApiRequest({
    api: `/herd/web/api/v1/rancher/${farmid}/rancher_plans/`,
    method: "get",
    params: params,
    queryKey: ["incentivePlans", params],
  });

  useEffect(() => {
    if (apiData?.results) {
      const formattedData = apiData.results.map((item: any, i: number) => {
        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.plan_name,
          item?.livestock_type_name,
          item?.allowed_quantity?.toLocaleString(),
          <Popover key={i}>
            <DeleteButtonForPopOver
              page="farmer_plans"
              access="Delete-Rancher-Incentive-Plan"
              title="از حذف طرح تشویقی اطمینان دارید؟"
              api={`/product/web/api/v1/rancher_incentive_plan/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTableData(formattedData);
    }
  }, [apiData, params]);

  return (
    <>
      <Grid container className="items-center gap-2">
        <Grid>
          <Button
            size="small"
            page="farmer_plans"
            access="Post-Rancher-Incentive-Plan"
            variant="submit"
            onClick={() =>
              openModal({
                title: "تخصیص طرح تشویقی",
                content: (
                  <LiveStockRancherAllocateIncentivePlan
                    getData={refetch}
                    rancher={farmid}
                  />
                ),
              })
            }
          >
            تخصیص طرح تشویقی
          </Button>
        </Grid>
      </Grid>
      <Grid className="w-full">
        <Table
          className="mt-2"
          excelInfo={{
            link: "product/excel/incentive_plan_excel",
          }}
          onChange={(e) => {
            setParams(e);
          }}
          title={`طرح های تشویقی دامدار (${name})`}
          isPaginated
          count={apiData?.count || 10}
          columns={["ردیف", "نام طرح", "نوع دام", "تعداد راس مجاز", "عملیات"]}
          rows={tableData}
        />
      </Grid>
    </>
  );
}
