import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import Button from "../../components/Button/Button";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { ShowWeight } from "../../components/ShowWeight/ShowWeight";
import { Grid } from "../../components/Grid/Grid";
import Table from "../../components/Table/Table";
import { ListBulletIcon } from "@heroicons/react/24/outline";
import { INVENTORY } from "../../routes/paths";
import { useNavigate } from "@tanstack/react-router";
import { PaginationParameters } from "../../components/PaginationParameters/PaginationParameters";

const formatDeviceSaleType = (value?: string) =>
  value === "all"
    ? "بر اساس تعداد راس دام و وزن"
    : value === "weight"
    ? "بر اساس وزن"
    : value === "count"
    ? "بر اساس تعداد راس دام"
    : "-";

export const InventoryWarehouseEntryTab = () => {
  const navigate = useNavigate();

  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

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

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

  const { data: inventoryDashboardData, refetch: inventoryDashboardRefetch } =
    useApiRequest({
      api: "/warehouse/web/api/v1/inventory_entry/inventory_dashboard/",
      method: "get",
      params: publicParams,
      queryKey: ["inventoryDashboard"],
    });

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

  useEffect(() => {
    if (apiInventoryData?.results) {
      const formattedData = apiInventoryData.results.map(
        (item: any, i: number) => {
          const groups = item?.group
            ?.map((group: any) =>
              group === "rural"
                ? "روستایی"
                : group === "industrial"
                ? "صنعتی"
                : "عشایری"
            )
            .join(", ");

          return [
            params.page === 1
              ? i + 1
              : i + params.page_size * (params.page - 1) + 1,
            item?.quota_id,
            <ShowWeight
              key={i}
              weight={item?.inventory_received}
              type={item?.sale_unit?.unit}
            />,
            <ShowWeight
              key={i}
              weight={item?.remaining_weight}
              type={item?.sale_unit?.unit}
            />,
            item?.product?.product || "-",
            item?.sale_unit?.unit || "-",
            item?.sale_type === "gov" ? "دولتی" : "آزاد",
            groups || "-",
            formatDeviceSaleType(item?.pos_sale_type),
            <Popover key={i}>
              <Tooltip title="لیست ورود به انبار" position="right">
                <Button
                  page="quota"
                  access="DIstribute-Quota"
                  icon={
                    <ListBulletIcon className="w-5 h-5 text-purple-400 dark:text-purple-100" />
                  }
                  onClick={() => {
                    const path = INVENTORY + "/" + item.id;
                    navigate({ to: path });
                  }}
                />
              </Tooltip>
            </Popover>,
          ];
        }
      );
      setPagesTableData(formattedData);
    }
  }, [apiInventoryData, params]);

  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) }));
          setParams((prev) => ({ ...prev, page: 1 }));
        }}
        filters={[
          {
            api: "/product/web/api/v1/product/",
            selectedKeys: [publicParams.product_id || ""],
            onChange: (keys) => {
              setPublicParams((prev) => ({
                ...prev,
                product_id: keys[0] as string,
              }));
              setParams((prev) => ({ ...prev, page: 1 }));
            },
            title: "محصول",
            size: "small",
          },
        ]}
      />

      <Grid isDashboard>
        <Table
          isDashboard
          title="خلاصه اطلاعات"
          noPagination
          noSearch
          columns={["تعداد ورود به انبار", "وزن ورود به انبار (کیلوگرم)"]}
          rows={[
            [
              inventoryDashboardData?.total_entries?.toLocaleString() || 0,
              inventoryDashboardData?.total_weight?.toLocaleString() || 0,
            ],
          ]}
        />
      </Grid>

      <Table
        className="mt-2"
        onChange={(e) => {
          setParams(e);
        }}
        noSearch
        count={apiInventoryData?.count || 10}
        isPaginated
        title="ورود به انبار"
        columns={[
          "ردیف",
          "شماره سهمیه",
          "وزن",
          "وزن باقیمانده سهمیه",
          "محصول",
          "واحد فروش",
          "نوع فروش",
          "گروه",
          "نوع فروش در دستگاه",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
