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 { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { TagDetails } from "../partials/tagging/TagDetails";
import { useParams } from "@tanstack/react-router";

export default function Tags() {
  const { openModal } = useModalStore();
  const [tableInfo, setTableInfo] = useState({ page: 1, page_size: 10 });
  const [tagsTableData, setTagsTableData] = useState([]);
  const { id, from, to } = useParams({ strict: false });
  const { data: tagsData, refetch } = useApiRequest({
    api: `/tag/web/api/v1/tag/${id ? id + "/tags_by_batch" : ""}`,
    method: "get",
    queryKey: ["tagsList", tableInfo],
    params: {
      ...tableInfo,
    },
  });

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

  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?.tag_code || "-",
          item?.organization?.name || "بدون سازمان",
          item?.species_code === 1
            ? "گاو"
            : item?.species_code === 2
            ? "گاومیش"
            : item?.species_code === 3
            ? "شتر"
            : item?.species_code === 4
            ? "گوسفند"
            : item?.species_code === 5
            ? "بز"
            : "نامشخص",
          item?.status === "F"
            ? "آزاد"
            : item?.status === "A"
            ? "پلاک شده"
            : item?.status === "R"
            ? "رزرو"
            : "-",
          item?.ownership_code || "-",
          <Popover key={item.id}>
            <Tooltip title="جزئیات پلاک" position="right">
              <Button
                variant="detail"
                page="tagging"
                access="Tag-Details"
                disabled={item?.status === "F"}
                onClick={() => {
                  openModal({
                    title: "جزئیات پلاک",
                    content: <TagDetails tagId={item.id} />,
                    isFullSize: true,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="tagging"
              access="Delete-Tag"
              api={`/tag/web/api/v1/tag/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTagsTableData(formattedData);
    }
  }, [tagsData]);

  return (
    <Grid container column className="gap-4 mt-2">
      <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={!id ? "لیست پلاک" : "لیست پلاک های بازه " + from + " تا " + to}
        columns={[
          "ردیف",
          "پلاک",
          "سازمان ثبت کننده",
          "کد گونه",
          "وضعیت",
          "کد مالکیت ثبتی",
          "عملیات",
        ]}
        rows={tagsTableData}
      />
    </Grid>
  );
}
