import { useEffect, useState } from "react";
import { useApiRequest } from "../utils/useApiRequest";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import Button from "../components/Button/Button";
import { useModalStore } from "../context/zustand-store/appStore";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import { SubmitNewTags } from "../partials/tagging/SubmitNewTags";
import { useNavigate } from "@tanstack/react-router";
import { TAGS } from "../routes/paths";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";

export default function Tagging() {
  const { openModal } = useModalStore();
  const [tableInfo, setTableInfo] = useState({ page: 1, page_size: 10 });
  const [tagsTableData, setTagsTableData] = useState([]);
  const navigate = useNavigate();

  const { data: tagsData, refetch } = useApiRequest({
    api: "/tag/web/api/v1/tag_batch/",
    method: "get",
    queryKey: ["tagsList", tableInfo],
    params: {
      ...tableInfo,
    },
  });

  const { data: tagDashboardData, refetch: updateDashboard } = useApiRequest({
    api: "/tag/web/api/v1/tag/tag_dashboard/",
    method: "get",
    queryKey: ["tagDashboard"],
  });

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

  useEffect(() => {
    if (tagsData?.results) {
      const formattedData = tagsData.results.map((item: any, index: number) => {
        return [
          tableInfo.page === 1
            ? index + 1
            : index + tableInfo.page_size * (tableInfo.page - 1) + 1,
          item?.organization?.name || "بدون سازمان",
          item?.species_code === 1
            ? "گاو"
            : item?.species_code === 2
            ? "گاومیش"
            : item?.species_code === 3
            ? "شتر"
            : item?.species_code === 4
            ? "گوسفند"
            : item?.species_code === 5
            ? "بز"
            : "نامشخص",
          item?.serial_from || "-",
          item?.serial_to || "-",
          <Popover key={item.id}>
            <Tooltip title="مشاهده پلاک ها" position="right">
              <Button
                variant="detail"
                page="tags"
                access="Show-Tags-Page"
                onClick={() => {
                  const path =
                    TAGS +
                    "/" +
                    item?.id +
                    "/" +
                    item?.serial_from +
                    "/" +
                    item?.serial_to;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                page="livestock_farmers"
                access="Edit-Rancher"
                onClick={() => {
                  openModal({
                    title: "ایجاد پلاک جدید",
                    content: (
                      <SubmitNewTags getData={handleUpdate} item={item} />
                    ),
                  });
                }}
              />
            </Tooltip>

            <DeleteButtonForPopOver
              page="tagging"
              access="Delete-Tag"
              api={`/tag/web/api/v1/tag_batch/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTagsTableData(formattedData);
    } else {
      setTagsTableData([]);
    }
  }, [tagsData]);

  return (
    <Grid container column className="gap-4 mt-2">
      <Grid>
        <Button
          size="small"
          variant="submit"
          page="tagging"
          access="Create-Tag"
          onClick={() => {
            openModal({
              title: "ایجاد پلاک جدید",
              content: <SubmitNewTags getData={handleUpdate} />,
            });
          }}
        >
          ایجاد پلاک جدید
        </Button>
      </Grid>

      <Grid isDashboard>
        <Table
          isDashboard
          title="خلاصه اطلاعات"
          noPagination
          noSearch
          columns={[
            "تعداد کل",
            "تعداد پلاک های آزاد",
            "تعداد پلاک شده",
            "گاو",
            "گاومیش",
            "شتر",
            "گوسفند",
            "بز",
          ]}
          rows={[
            [
              tagDashboardData?.count?.toLocaleString() || 0,
              tagDashboardData?.free_count?.toLocaleString() || 0,
              tagDashboardData?.assign_count?.toLocaleString() || 0,
              tagDashboardData?.cow_count?.toLocaleString() || 0,
              tagDashboardData?.buffalo_count?.toLocaleString() || 0,
              tagDashboardData?.camel_count?.toLocaleString() || 0,
              tagDashboardData?.sheep_count?.toLocaleString() || 0,
              tagDashboardData?.goat_count?.toLocaleString() || 0,
            ],
          ]}
        />
      </Grid>

      <Table
        className="mt-2"
        onChange={setTableInfo}
        count={tagsData?.count || 0}
        isPaginated
        title="پلاک کوبی"
        columns={[
          "ردیف",
          "سازمان ثبت کننده",
          "کد گونه",
          "از بازه سریال",
          "تا بازه سریال",
          "عملیات",
        ]}
        rows={tagsTableData}
      />
    </Grid>
  );
}
