import { useEffect, useState } from "react";
import { useParams } from "@tanstack/react-router";
import { Bars3Icon, CubeIcon, SparklesIcon } from "@heroicons/react/24/outline";
import { useApiRequest } from "../utils/useApiRequest";
import { useModalStore } from "../context/zustand-store/appStore";
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 Table from "../components/Table/Table";
import { Popover } from "../components/PopOver/PopOver";
import Button from "../components/Button/Button";
import { Tooltip } from "../components/Tooltip/Tooltip";
import { DistributeFromDistribution } from "../partials/tagging/DistributeFromDistribution";
import { DocumentOperation } from "../components/DocumentOperation/DocumentOperation";
import { DocumentDownloader } from "../components/DocumentDownloader/DocumentDownloader";
import { BooleanQuestion } from "../components/BooleanQuestion/BooleanQuestion";
import { useUserProfileStore } from "../context/zustand-store/userStore";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";

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

export default function TagDistribtutionDetails() {
  const { id } = useParams({ strict: false });
  const { openModal } = useModalStore();
  const [childTableInfo, setChildTableInfo] = useState({
    page: 1,
    page_size: 10,
  });
  const [childTableData, setChildTableData] = useState([]);

  const { data, refetch: refetchData } = useApiRequest({
    api: `/tag/web/api/v1/tag_distribution_batch/${id}/`,
    method: "get",
    queryKey: ["tagBatchInnerDashboard", id],
    enabled: !!id,
  });

  const { data: childData, refetch: refetchChildList } = useApiRequest({
    api: `/tag/web/api/v1/tag_distribution_batch/${id}/child_list/`,
    method: "get",
    queryKey: ["tagDistributionChildList", id, childTableInfo],
    params: {
      ...childTableInfo,
    },
    enabled: !!id,
  });

  const { profile } = useUserProfileStore();

  const showAssignDocColumn =
    childData?.results?.some(
      (item: any) =>
        profile?.role?.type?.key === "ADM" ||
        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}
        />
      );
    } else {
      return "-";
    }
  };

  const handleUpdate = () => {
    refetchData();
    refetchChildList();
  };

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

          return [
            childTableInfo.page === 1
              ? index + 1
              : index +
                childTableInfo.page_size * (childTableInfo.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?.toLocaleString() ?? "-",
            item?.total_distributed_tag_count?.toLocaleString() ?? "-",
            item?.remaining_tag_count?.toLocaleString() ?? "-",
            item?.distribution_type === "batch"
              ? "توزیع گروهی"
              : "توزیع تصادفی",
            <ShowMoreInfo key={item?.id} title="جزئیات توزیع">
              <Grid container column className="gap-4 w-full">
                {dist?.map((opt: any, idx: number) => (
                  <Grid
                    key={idx}
                    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 != null && (
                        <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={`doc-${item?.id}`}
              link={item?.warehouse_exit_doc}
              title="دانلود"
            />,
            item?.exit_doc_status ? (
              "تایید شده"
            ) : (
              <Button
                key={`btn-${item?.id}`}
                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={`popover-${item?.id}`}>
              <Tooltip title="ویرایش توزیع" position="right">
                <Button
                  variant="edit"
                  page="tag_distribution"
                  access="Submit-Tag-Distribution"
                  onClick={() => {
                    openModal({
                      title: "ویرایش توزیع",
                      content: (
                        <DistributeFromDistribution
                          getData={handleUpdate}
                          item={item}
                          isEdit
                          parentDistributions={data?.distributions}
                        />
                      ),
                    });
                  }}
                />
              </Tooltip>
              <DeleteButtonForPopOver
                page="tag_distribution"
                access="Delete-Tag-Distribution"
                api={`/tag/web/api/v1/tag_distribution_batch/${item?.id}/`}
                getData={handleUpdate}
              />
            </Popover>,
          ];
        },
      );
      setChildTableData(formattedData);
    } else {
      setChildTableData([]);
    }
  }, [childData, childTableInfo]);

  const dist = data?.distributions;

  return (
    <Grid container column className="gap-4 mt-2">
      <Grid isDashboard>
        <Table
          isDashboard
          title="مشخصات توزیع پلاک"
          noSearch
          noPagination
          columns={[
            "شناسه توزیع",
            "تاریخ ثبت",
            "توزیع کننده",
            "دریافت کننده",
            "تعداد کل پلاک",
            "پلاک های توزیع شده",
            "پلاک های باقیمانده",
            "نوع توزیع",
            "جزئیات توزیع",
          ]}
          rows={[
            [
              data?.dist_batch_identity ?? "-",
              `${formatJustDate(data?.create_date) ?? "-"} (${
                formatJustDate(data?.create_date)
                  ? (formatJustTime(data?.create_date) ?? "-")
                  : "-"
              })`,
              data?.assigner_org?.name ?? "-",
              data?.assigned_org?.name ?? "-",
              data?.total_tag_count?.toLocaleString() ?? "-",
              data?.total_distributed_tag_count?.toLocaleString() ?? "-",
              data?.remaining_tag_count?.toLocaleString() ?? "-",
              data?.distribution_type === "batch"
                ? "توزیع گروهی"
                : "توزیع تصادفی",
              <ShowMoreInfo key={data?.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>

                      {data?.distribution_type === "batch" &&
                        opt?.serial_from != null && (
                          <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>,
            ],
          ]}
        />
      </Grid>

      <Table
        className="mt-2"
        onChange={setChildTableInfo}
        count={childData?.count || 0}
        isPaginated
        title="توزیع های مجدد"
        columns={[
          "ردیف",
          "شناسه توزیع",
          "تاریخ ثبت",
          "توزیع کننده",
          "دریافت کننده",
          "تعداد کل پلاک",
          "پلاک های توزیع شده",
          "پلاک های باقیمانده",
          "نوع توزیع",
          "جزئیات توزیع",
          ...(showAssignDocColumn ? ["امضا سند خروج از انبار"] : []),
          "سند خروج از انبار",
          "تایید سند خروج",
          "عملیات",
        ]}
        rows={childTableData}
      />
    </Grid>
  );
}
