import { useEffect, useState } from "react";
import {
  Bars3Icon,
  CubeIcon,
  SparklesIcon,
  StopCircleIcon,
} 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 { SubmitTagDistribution } from "./SubmitTagDistribution";
import { DistributeFromDistribution } from "./DistributeFromDistribution";
import Table from "../../components/Table/Table";
import { BooleanQuestion } from "../../components/BooleanQuestion/BooleanQuestion";
import { TableButton } from "../../components/TableButton/TableButton";
import { DistributionSpeciesModal } from "./DistributionSpeciesModal";
import { useNavigate } from "@tanstack/react-router";
import { TAG_DISTRIBUTION } from "../../routes/paths";
import { DocumentOperation } from "../../components/DocumentOperation/DocumentOperation";
import { DocumentDownloader } from "../../components/DocumentDownloader/DocumentDownloader";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

export default function TagActiveDistributions() {
  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_distribution_batch",
    method: "get",
    queryKey: ["tagsList", tableInfo],
    params: {
      ...tableInfo,
    },
  });

  const { profile } = useUserProfileStore();

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

  const showAssignDocColumn =
    (profile?.role?.type?.key === "ADM" ||
      tagsData?.results?.some(
        (item: any) => profile?.organization?.id === item?.assigned_org?.id,
      )) ??
    false;

  const AbleToSeeAssignDoc = (item: any) => {
    if (
      profile?.role?.type?.key === "ADM" ||
      profile?.organization?.id === item?.assigned_org?.id
    ) {
      return (
        <DocumentOperation
          key={item?.id}
          downloadLink={`/tag/web/api/v1/tag_distribution_batch/${item?.id}/distribution_pdf_view/`}
          payloadKey="dist_exit_document"
          // validFiles={["pdf"]}
          page="tag_distribution"
          access="Upload-Assign-Document"
          uploadLink={`/tag/web/api/v1/tag_distribution_batch/${item?.id}/assign_document/`}
          onUploadSuccess={handleUpdate}
          limitSize={3}
        />
      );
    } else {
      return "-";
    }
  };

  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?.total_distributed_tag_count,
          item?.remaining_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"
                >
                  <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>

                  {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?.total_tag_count?.toLocaleString()}
                    </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">
                    <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?.remaining_number?.toLocaleString()}
                    </Typography>
                  </Grid>
                </Grid>
              ))}
            </Grid>
          </ShowMoreInfo>,
          ...(showAssignDocColumn ? [AbleToSeeAssignDoc(item)] : []),
          <DocumentDownloader
            key={index}
            link={item?.warehouse_exit_doc}
            title="دانلود"
          />,
          item?.exit_doc_status ? (
            "تایید شده"
          ) : (
            <Button
              page="tag_distribution"
              access="Accept-Assign-Document"
              size="small"
              disabled={item?.exit_doc_status}
              onClick={() => {
                openModal({
                  title: "تایید سند خروج",
                  content: (
                    <BooleanQuestion
                      api={`/tag/web/api/v1/tag_distribution_batch/${item?.id}/accept_exit_doc/`}
                      method="post"
                      getData={handleUpdate}
                      title="آیا از تایید سند خروج مطمئنید؟"
                    />
                  ),
                });
              }}
            >
              تایید سند خروج
            </Button>
          ),
          <Popover key={index}>
            <Tooltip title="جزئیات توزیع" position="right">
              <Button
                variant="detail"
                page="tag_distribution_detail"
                access="Show-Tag-Distribution-Detail"
                onClick={() => {
                  const path =
                    TAG_DISTRIBUTION +
                    "/" +
                    item?.dist_batch_identity +
                    "/" +
                    item?.id;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
            <Tooltip title="ویرایش توزیع" position="right">
              <Button
                variant="edit"
                page="tag_distribution"
                access="Submit-Tag-Distribution"
                onClick={() => {
                  openModal({
                    title: "ویرایش توزیع پلاک",
                    content: (
                      <SubmitTagDistribution
                        getData={handleUpdate}
                        item={item}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <Tooltip title="توزیع مجدد" position="right">
              <Button
                variant="share"
                page="tag_distribution"
                access="Distribute-From-Distribution"
                onClick={() => {
                  openModal({
                    title: "توزیع مجدد",
                    content: (
                      <DistributeFromDistribution
                        getData={handleUpdate}
                        item={item}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <Tooltip title={"لغو توزیع"} position="right">
              <Button
                page="tag_distribution"
                access="Cancel-Tag-Distribution"
                icon={<StopCircleIcon 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}/close_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={refetch}
            />
          </Popover>,
        ];
      });

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

  return (
    <Grid container column className="gap-4 mt-2">
      <Grid>
        <Button
          size="small"
          variant="submit"
          page="tag_distribution"
          access="Submit-Tag-Distribution"
          onClick={() => {
            openModal({
              title: "توزیع پلاک",
              content: <SubmitTagDistribution getData={handleUpdate} />,
            });
          }}
        >
          توزیع پلاک
        </Button>
      </Grid>

      <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={[
          "ردیف",
          "شناسه توزیع",
          "تاریخ ثبت",
          "توزیع کننده",
          "دریافت کننده",
          "تعداد کل پلاک",
          "پلاک های توزیع شده",
          "پلاک های باقیمانده",
          "نوع توزیع",
          "جزئیات توزیع",
          ...(showAssignDocColumn ? ["امضا سند خروج از انبار"] : []),
          "سند خروج از انبار",
          "تایید سند خروج",
          "عملیات",
        ]}
        rows={tagsTableData}
      />
    </Grid>
  );
}
