import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import { useModalStore } from "../../context/zustand-store/appStore";
import Table from "../../components/Table/Table";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { AddQuota } from "./AddQuota";
import { QuotaView } from "./QuotaView";
import { PopoverCustomModalOperation } from "../../components/PopOverCustomModalOperation/PopoverCustomModalOperation";
import {
  ArrowDownOnSquareIcon,
  ArrowUpOnSquareIcon,
  BarsArrowUpIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import { useNavigate } from "@tanstack/react-router";
import { QUOTAS } from "../../routes/paths";
import { getQuotaTableColumns, getQuotaTableRowData } from "./quotaTableUtils";
import { QuotaAllocateToStakeHolders } from "./QuotaAllocateToStakeHolders";
import { QuotaDistributionEntryInventory } from "./QuotaDistributionEntryInventory";
import { useUserProfileStore } from "../../context/zustand-store/userStore";
import { TableButton } from "../../components/TableButton/TableButton";
import { QuotaActivesDashboardDetails } from "./QuotaActivesDashboardDetails";
import { PaginationParameters } from "../../components/PaginationParameters/PaginationParameters";

export const QuotaActives = () => {
  const { openModal } = useModalStore();
  const navigate = useNavigate();
  const { profile } = useUserProfileStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

  const [publicParams, setPublicParams] = useState({
    start: null,
    end: null,
    search: null,
  });

  const { data: pagesData, refetch } = useApiRequest({
    api: "/product/web/api/v1/quota/active_quotas/",
    method: "get",
    params: { ...pagesInfo, ...publicParams },
    queryKey: ["activeQuotas", pagesInfo],
  });

  const { data: quotasDashboardData, refetch: quotasDashboardRefetch } =
    useApiRequest({
      api: "/product/web/api/v1/quota/quotas_dashboard/",
      method: "get",
      params: publicParams,
      queryKey: ["quotasDashboard"],
    });

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

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return getQuotaTableRowData(item, i, {
          pagesInfo,
          renderOperations: (item, index) => (
            <Popover key={index}>
              <Tooltip title="نمای کلی" position="right">
                <Button
                  variant="view"
                  page="quota"
                  access="Post-Quota"
                  onClick={() => {
                    openModal({
                      title: "نمای کلی سهمیه",
                      content: <QuotaView item={item} />,
                      isFullSize: true,
                    });
                  }}
                />
              </Tooltip>

              {(profile?.role?.type?.key === "ADM" || item?.assigned_to_me) && (
                <Tooltip title="ویرایش سهمیه" position="right">
                  <Button
                    variant="edit"
                    page="quota"
                    access="Edit-Quota"
                    onClick={() => {
                      openModal({
                        title: "ویرایش سهمیه",
                        content: (
                          <AddQuota item={item} getData={handleUpdate} />
                        ),
                        isFullSize: true,
                      });
                    }}
                  />
                </Tooltip>
              )}

              <Tooltip
                title={
                  profile?.role?.type?.key === "ADM" || item?.assigned_to_me
                    ? "توزیع سهمیه"
                    : "جزئیات"
                }
                position="right"
              >
                <Button
                  page="quota"
                  access="DIstribute-Quota"
                  icon={
                    <ArrowUpOnSquareIcon className="w-5 h-5 text-purple-400 dark:text-purple-100" />
                  }
                  onClick={() => {
                    const path = QUOTAS + "/" + item.id;
                    navigate({ to: path });
                  }}
                />
              </Tooltip>

              {(profile?.role?.type?.key === "ADM" || item?.assigned_to_me) && (
                <Tooltip title="ورود به انبار" position="right">
                  <Button
                    size="small"
                    page="inventory"
                    access="Entry-Inventory"
                    icon={
                      <ArrowDownOnSquareIcon className="w-6 h-6 text-primary-600" />
                    }
                    onClick={() => {
                      openModal({
                        title: "ورود به انبار",
                        content: (
                          <QuotaDistributionEntryInventory
                            getData={handleUpdate}
                            code={item?.id}
                            remainWeight={item?.remaining_weight}
                          />
                        ),
                      });
                    }}
                  />
                </Tooltip>
              )}

              {profile?.role?.type?.key === "CO" && (
                <Tooltip title="تخصیص به زیر مجموعه" position="right">
                  <Button
                    size="small"
                    page="inventory"
                    access="Stakeholder-Allocation"
                    icon={
                      <BarsArrowUpIcon className="w-6 h-6 text-purple-400 dark:text-white" />
                    }
                    onClick={() => {
                      openModal({
                        title: "تخصیص به زیر مجموعه",
                        content: (
                          <QuotaAllocateToStakeHolders
                            getData={handleUpdate}
                            item={item}
                            isSubmit
                          />
                        ),
                      });
                    }}
                  />
                </Tooltip>
              )}

              <Tooltip title="خروجی اکسل" position="right">
                <Button
                  excelInfo={{
                    link: `product/excel/detail_quota_excel/?active=true&id=${item?.id}`,
                    title: `اطلاعات سهمیه ${item?.quota_id}`,
                  }}
                />
              </Tooltip>
              {(profile?.role?.type?.key === "ADM" || item?.assigned_to_me) && (
                <PopoverCustomModalOperation
                  method="patch"
                  tooltipText="بستن سهمیه"
                  icon={<XMarkIcon className="w-6 h-6 text-red-500" />}
                  title="از بستن سهمیه اطمینان دارید؟"
                  api={`product/web/api/v1/quota/${item?.id}/close/`}
                  getData={handleUpdate}
                  page="quota"
                  access="CLose-Quota"
                />
              )}
            </Popover>
          ),
        });
      });
      setPagesTableData(tableData);
    }
  }, [pagesData]);

  return (
    <Grid container column className="gap-4 mt-2">
      <PaginationParameters
        title="سهمیه های فعال"
        excelInfo={{
          link: `/product/excel/quota_excel/?active=true&start=${
            publicParams.start || ""
          }&end=${publicParams.end || ""}&search=${publicParams.search || ""}`,
          title: "سهمیه های فعال",
        }}
        getData={handleUpdate}
        onChange={(r) => {
          setPublicParams((prev) => ({ ...prev, ...(r as any) }));
          setPagesInfo((prev) => ({ ...prev, page: 1 }));
        }}
      />

      <Grid isDashboard>
        <Table
          isDashboard
          title="خلاصه اطلاعات"
          noPagination
          noSearch
          columns={[
            "تعداد کل سهمیه ها",
            "مجموع وزن سهمیه ها (کیلوگرم)",
            "مجموع وزن توزیع شده (کیلوگرم)",
            "مجموع وزن باقیمانده (کیلوگرم)",
            "مجموع وزن فروش رفته (کیلوگرم)",
            "مجموع وزن ورود به انبار (کیلوگرم)",
            "جزئیات",
          ]}
          rows={[
            [
              quotasDashboardData?.quotas_summary?.total_quotas?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.total_amount?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.total_distributed?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.remaining_amount?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.sold_amount?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.inventory_received?.toLocaleString() ||
                0,
              <TableButton
                size="small"
                key="details"
                onClick={() => {
                  openModal({
                    title: "جزئیات",
                    content: (
                      <QuotaActivesDashboardDetails
                        publicParams={publicParams}
                      />
                    ),
                    isFullSize: true,
                  });
                }}
              >
                جزئیات
              </TableButton>,
            ],
          ]}
        />
      </Grid>
      <Grid>
        <Button
          size="small"
          page="quota"
          access="Post-Quota"
          variant="submit"
          onClick={() => {
            openModal({
              title: "ایجاد سهمیه",
              content: <AddQuota getData={refetch} />,
              isFullSize: true,
            });
          }}
        >
          ایجاد سهمیه
        </Button>
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        noSearch
        count={pagesData?.count || 10}
        isPaginated
        title="سهمیه های فعال"
        columns={getQuotaTableColumns({ includeOperations: true })}
        rows={pagesTableData}
      />
    </Grid>
  );
};
