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 { useParams } from "@tanstack/react-router";
import { formatAgeCalcuation, formatJustDate } from "../utils/formatTime";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { LiveStockAddLiveStock } from "../partials/live-stock/LiveStockAddLiveStock";
import { useDrawerStore } from "../context/zustand-store/appStore";
import { CheckCircleIcon, XCircleIcon } from "@heroicons/react/24/outline";

export default function LiveStocks() {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

  const { openDrawer } = useDrawerStore();

  const { herdid, name } = useParams({ strict: false });
  const { data: pagesData, refetch } = useApiRequest({
    api: herdid
      ? `herd/web/api/v1/herd/${herdid}/live_stocks/`
      : "/livestock/web/api/v1/livestock/",
    method: "get",
    params: pagesInfo,
    queryKey: ["LiveStockFarmers", pagesInfo],
  });

  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?.type?.name,
          // item?.use_type?.name,
          formatJustDate(item?.birthdate),
          formatAgeCalcuation(item?.birthdate),
          item?.tag?.tag_code || "-",
          item?.gender === 1 ? "نر" : "ماده",
          // item?.species?.name,
          item?.weight_type === "L" ? "سبک" : "سنگین",
          <span className="flex items-center gap-1">
            {item?.active ? (
              <>
                <span className="text-green-500">فعال</span>
                <CheckCircleIcon className="w-5 h-5 text-green-500" />
              </>
            ) : (
              <>
                <span className="text-red-500">غیرفعال</span>
                <XCircleIcon className="w-5 h-5 text-red-500" />
              </>
            )}
          </span>,
          <Popover key={i}>
            <Tooltip title="ویرایش دام" position="right">
              <Button
                variant="edit"
                page="livestocks"
                access="Edit-LiveStock"
                onClick={() =>
                  openDrawer({
                    title: "ویرایش دام",
                    content: (
                      <LiveStockAddLiveStock
                        getData={refetch}
                        herdId={item?.herd?.id}
                        item={item}
                      />
                    ),
                    isOpen: true,
                    direction: "left",
                  })
                }
              />
            </Tooltip>
            <DeleteButtonForPopOver
              api={`livestock/web/api/v1/livestock/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData, pagesInfo]);

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