import { useEffect, useState } from "react";
import {
  BackwardIcon,
  Bars3Icon,
  CubeIcon,
  SparklesIcon,
} from "@heroicons/react/24/outline";
import { useModalStore } from "../../context/zustand-store/appStore";
import { useApiRequest } from "../../utils/useApiRequest";
import { formatJustDate, formatJustTime } from "../../utils/formatTime";
import ShowMoreInfo from "../../components/ShowMoreInfo/ShowMoreInfo";
import { Grid } from "../../components/Grid/Grid";
import Typography from "../../components/Typography/Typography";
import { Popover } from "../../components/PopOver/PopOver";
import Button from "../../components/Button/Button";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";

import Table from "../../components/Table/Table";
import { BooleanQuestion } from "../../components/BooleanQuestion/BooleanQuestion";
import { TableButton } from "../../components/TableButton/TableButton";
import { DistributionSpeciesModal } from "./DistributionSpeciesModal";

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

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

  const { data: tagDashboardData, refetch: updateDashboard } = useApiRequest({
    api: "/tag/web/api/v1/tag_distribution_batch/main_dashboard/?is_closed=true",
    method: "get",
    queryKey: ["tagDistributionCanceledDashboard"],
  });

  const handleUpdate = () => {
    refetch();
    updateDashboard();
  };
  const speciesMap: Record<number, string> = {
    1: "گاو",
    2: "گاومیش",
    3: "شتر",
    4: "گوسفند",
    5: "بز",
  };

  useEffect(() => {
    if (tagsData?.results) {
      const formattedData = tagsData.results.map((item: any, index: number) => {
        const dist = item?.distributions;

        return [
          tableInfo.page === 1
            ? index + 1
            : index + tableInfo.page_size * (tableInfo.page - 1) + 1,
          item?.dist_batch_identity,
          `${formatJustDate(item?.create_date)} (${
            formatJustDate(item?.create_date)
              ? formatJustTime(item?.create_date)
              : "-"
          })`,
          item?.assigner_org?.name,
          item?.assigned_org?.name,
          item?.total_tag_count,
          item?.distribution_type === "batch" ? "توزیع گروهی" : "توزیع تصادفی",
          <ShowMoreInfo key={item?.id} title="جزئیات توزیع">
            <Grid container column className="gap-4 w-full">
              {dist?.map((opt: any, index: number) => (
                <Grid
                  key={index}
                  container
                  column
                  className="gap-3 w-full rounded-xl border border-gray-200 dark:border-gray-700 p-4"
                >
                  {item?.distribution_type === "batch" && opt?.serial_from && (
                    <Grid container className="gap-2 items-center">
                      <Bars3Icon className="w-5 h-5 text-gray-500 dark:text-gray-300" />
                      <Typography variant="body2" className="font-medium">
                        بازه سریال:
                      </Typography>
                      <Typography
                        variant="body2"
                        className="text-gray-600 dark:text-gray-400"
                      >
                        از {opt?.serial_from ?? "-"} تا {opt?.serial_to ?? "-"}
                      </Typography>
                    </Grid>
                  )}

                  <Grid container className="gap-2 items-center">
                    <CubeIcon className="w-5 h-5 text-gray-500 dark:text-gray-300" />
                    <Typography variant="body2" className="font-medium">
                      تعداد پلاک:
                    </Typography>
                    <Typography
                      variant="body2"
                      className="text-gray-700 dark:text-gray-300"
                    >
                      {opt?.distributed_number?.toLocaleString()}
                    </Typography>
                  </Grid>

                  <Grid container className="gap-2 items-center">
                    <SparklesIcon className="w-5 h-5 text-gray-500 dark:text-gray-300" />
                    <Typography variant="body2" className="font-medium">
                      گونه:
                    </Typography>
                    <Typography
                      variant="body2"
                      className="text-gray-700 dark:text-gray-300"
                    >
                      {speciesMap[opt?.species_code] ?? "-"}
                    </Typography>
                  </Grid>
                </Grid>
              ))}
            </Grid>
          </ShowMoreInfo>,
          <Popover key={index}>
            <Tooltip title={"برگشت توزیع"} position="right">
              <Button
                page="tag_distribution"
                access="Cancel-Tag-Distribution"
                icon={<BackwardIcon className="w-5 h-5 text-red-400" />}
                variant="set"
                onClick={() => {
                  openModal({
                    title: "برگشت توزیع لغو شده",
                    content: (
                      <BooleanQuestion
                        api={`/tag/web/api/v1/tag_distribution_batch/${item?.id}/reactivate_tag_dist_batch/`}
                        method="post"
                        getData={handleUpdate}
                        title="آیا از برگشت توزیع پلاک لغو شده مطمئنید؟"
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="tag_distribution"
              access="Delete-Tag-Distribution"
              api={`/tag/web/api/v1/tag_distribution_batch/${item?.id}/`}
              getData={handleUpdate}
            />
          </Popover>,
        ];
      });

      setTagsTableData(formattedData);
    } else {
      setTagsTableData([]);
    }
  }, [tagsData, tableInfo]);

  return (
    <Grid container column className="gap-4 mt-2">
      <Grid isDashboard>
        <Table
          isDashboard
          title="خلاصه اطلاعات"
          noPagination
          noSearch
          columns={[
            "تعداد توزیع",
            "پلاک های ارسالی",
            "پلاک های دریافتی",
            "توزیع های دریافتی",
            "توزیع های ارسالی",
            "جزئیات",
          ]}
          rows={[
            [
              tagDashboardData?.count?.toLocaleString() || 0,
              tagDashboardData?.total_sent_tag_count?.toLocaleString() || 0,
              tagDashboardData?.total_recieved_tag_count?.toLocaleString() || 0,
              tagDashboardData?.total_recieved_distributions?.toLocaleString() ||
                0,
              tagDashboardData?.total_sent_distributions?.toLocaleString() || 0,
              <TableButton
                size="small"
                onClick={() => {
                  openModal({
                    title: "جزئیات",
                    content: (
                      <DistributionSpeciesModal
                        items={tagDashboardData?.items}
                      />
                    ),
                  });
                }}
              />,
            ],
          ]}
        />
      </Grid>
      <Table
        className="mt-2"
        onChange={setTableInfo}
        count={tagsData?.count || 0}
        isPaginated
        title="توزیع های لغو شده"
        columns={[
          "ردیف",
          "شناسه توزیع",
          "تاریخ ثبت",
          "توزیع کننده",
          "دریافت کننده",
          "تعداد کل پلاک",
          "نوع توزیع",
          "جزئیات توزیع",
          "عملیات",
        ]}
        rows={tagsTableData}
      />
    </Grid>
  );
}
