import { useParams } from "@tanstack/react-router";
import { Grid } from "../../components/Grid/Grid";
import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import Table from "../../components/Table/Table";
import { formatJustDate, formatJustTime } from "../../utils/formatTime";
import { getPersianMonths } from "../../utils/getPersianMonths";
import ShowMoreInfo from "../../components/ShowMoreInfo/ShowMoreInfo";
import Typography from "../../components/Typography/Typography";
import ShowStringList from "../../components/ShowStringList/ShowStringList";
import Divider from "../../components/Divider/Divider";
import { ShowWeight } from "../../components/ShowWeight/ShowWeight";

export const QuotaReportingQuotaDistributions = () => {
  const params = useParams({ strict: false });

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

  const { data: pagesData } = useApiRequest({
    api: `/product/web/api/v1/quota/${params?.itemid}/distributions_by_quota/`,
    method: "get",
    params: pagesInfo,
    queryKey: ["distributions_by_quota", pagesInfo],
  });

  const { data: DashboardData } = useApiRequest({
    api: `/product/web/api/v1/quota/${params?.itemid}/`,
    method: "get",
    queryKey: ["distributions_dashboard"],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.distribution_id,
          `${formatJustDate(item?.create_date)} (${formatJustTime(
            item?.create_date
          )})`,
          item?.assigner_organization?.organization +
            " (" +
            item?.creator_info +
            ")",
          item?.assigned_organization?.organization,
          <ShowWeight
            key={i}
            weight={item?.weight}
            type={item?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.been_sold}
            type={item?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.warehouse_balance}
            type={item?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.warehouse_entry}
            type={item?.sale_unit?.unit}
          />,
          item?.description,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData]);

  return (
    <Grid container column className="gap-4">
      <Grid isDashboard>
        <Table
          isDashboard
          noPagination
          className="mt-2"
          onChange={(e) => {
            setPagesInfo(e);
          }}
          count={pagesData?.count || 10}
          isPaginated
          title={`اطلاعات سهمیه`}
          columns={[
            "شناسه سهمیه",
            "وزن محصول",
            "وزن باقیمانده",
            "وزن توزیع شده",
            "تاریخ ثبت",
            "واحد فروش",
            "گروه",
            "سهمیه ماه",
            "نوع فروش",
            "مجوز فروش",
            "محدودیت توزیع دوره",
            "سهمیه بندی",
            "محدودیت ها",
            "محدود بر اساس تعداد راس دام",
            "نوع فروش در دستگاه",
            "طرح های تشویقی",
            "قیمت درب کارخانه",
            "قیمت درب تعاونی",
          ]}
          rows={[
            [
              DashboardData?.quota_id,
              <ShowWeight
                key={DashboardData}
                weight={DashboardData?.quota_weight}
                type={DashboardData?.sale_unit?.unit}
              />,
              <ShowWeight
                key={DashboardData}
                weight={DashboardData?.remaining_weight}
                type={DashboardData?.sale_unit?.unit}
              />,
              <ShowWeight
                key={DashboardData}
                weight={DashboardData?.quota_distributed}
                type={DashboardData?.quota_distributed?.unit}
              />,
              formatJustDate(DashboardData?.create_date),
              DashboardData?.sale_unit?.unit,
              DashboardData?.group === "rural"
                ? "روستایی"
                : DashboardData?.group === "industrial"
                ? "صنعتی"
                : "عشایری",
              getPersianMonths(DashboardData?.month_choices).join("، "),
              DashboardData?.sale_type === "gov" ? "دولتی" : "آزاد",
              getPersianMonths(DashboardData?.sale_license).join("، "),
              getPersianMonths(DashboardData?.distribution_mode).join("، "),
              <ShowMoreInfo
                key={DashboardData}
                title="سهمیه بندی دام"
                data={DashboardData?.livestock_allocations}
                columns={["گروه", "حجم", "دسته", "محصول"]}
                accessKeys={[
                  ["livestock_group"],
                  ["quantity_kg"],
                  ["livestock_type", "weight_type"],
                  ["livestock_type", "name"],
                ]}
                conditions={[
                  {
                    for: 0,
                    condition: "rural",
                    apply: "روستایی",
                    otherwise: "صنعتی",
                  },
                  {
                    for: 2,
                    condition: "L",
                    apply: "سبک",
                    otherwise: "سنگین",
                  },
                ]}
              />,
              <ShowMoreInfo key={DashboardData} title="محدودیت ها">
                <Grid
                  container
                  column
                  className="gap-2 p-2 justify-start DashboardDatas-start"
                >
                  <Typography variant="body2" sign="info">
                    محدودیت بر اساس شهرستان و تعاونی
                  </Typography>
                  <ShowStringList
                    strings={DashboardData?.limit_by_organizations?.map(
                      (opt: { name: string }) => opt?.name
                    )}
                  />

                  <Divider />
                  <Typography variant="body2" sign="info">
                    محدودیت بر اساس بازه سنی دام
                  </Typography>
                  <ShowStringList
                    strings={DashboardData?.livestock_limitations?.map(
                      (opt: {
                        age_month: string;
                        livestock_type: { name: string; weight_type: string };
                      }) =>
                        `${opt?.livestock_type?.name} (${
                          opt?.livestock_type?.weight_type === "L"
                            ? "سبک"
                            : "سنگین"
                        }) با سن ${opt?.age_month}`
                    )}
                  />
                </Grid>
              </ShowMoreInfo>,
              DashboardData?.limit_by_herd_size ? "دارد" : "ندارد",
              DashboardData?.pos_sale_type === "all"
                ? "بر اساس تعداد راس دام و وزن"
                : DashboardData?.pos_sale_type === "weight"
                ? "بر اساس وزن"
                : DashboardData?.pos_sale_type === "count"
                ? "بر اساس تعداد راس دام"
                : "-",
              <ShowMoreInfo key={DashboardData} title="طرح های تشویقی">
                <div className="grid grid-cols-2 gap-1.5 p-2 max-h-[400px] overflow-y-auto w-full">
                  {DashboardData?.incentive_plan?.map(
                    (itm: any, idx: number) => (
                      <Grid
                        container
                        column
                        key={idx}
                        className="bg-gradient-to-br from-primary-50/50 to-primary-100/30 dark:from-dark-900 dark:to-dark-800 rounded-lg p-2 border border-primary-200/50 dark:border-dark-700 shadow-sm hover:shadow-md transition-all duration-200"
                      >
                        <Grid container className="items-center gap-1.5 mb-1.5">
                          <div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary-500 text-white font-semibold text-xs shadow-sm">
                            {idx + 1}
                          </div>
                          <Typography
                            variant="body1"
                            fontWeight="semibold"
                            className="text-primary-900 dark:text-primary-100"
                          >
                            {itm?.name}
                          </Typography>
                        </Grid>
                        {itm?.live_stocks?.length > 0 && (
                          <Grid container column className="gap-1 pr-2">
                            {itm?.live_stocks?.map(
                              (liveStock: any, inidx: number) => (
                                <Grid
                                  container
                                  key={inidx}
                                  className="items-center justify-between bg-white/60 dark:bg-dark-700/50 rounded-md px-2 py-1 border border-primary-100 dark:border-dark-600"
                                >
                                  <Typography
                                    variant="caption"
                                    className="text-gray-700 dark:text-gray-200 font-medium"
                                  >
                                    {liveStock?.name}
                                  </Typography>
                                  <div className="flex items-center gap-1 px-1.5 py-0.5 rounded-full bg-primary-500/10 dark:bg-primary-500/20 border border-primary-300/30 dark:border-primary-500/30">
                                    <Typography
                                      variant="caption"
                                      fontWeight="semibold"
                                      className="text-primary-700 dark:text-primary-300"
                                    >
                                      {liveStock?.quantity?.toLocaleString()}
                                    </Typography>
                                  </div>
                                </Grid>
                              )
                            )}
                          </Grid>
                        )}
                      </Grid>
                    )
                  )}
                </div>
              </ShowMoreInfo>,
              parseInt(DashboardData?.base_price_factory)?.toLocaleString(),
              parseInt(DashboardData?.base_price_cooperative)?.toLocaleString(),
            ],
          ]}
        />
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        title={`توزیع سهمیه`}
        columns={[
          "ردیف",
          "شناسه توزیع",
          "تاریخ ثبت",
          "توزیع کننده",
          "دریافت کننده",
          "وزن",
          "وزن فروش رفته",
          "مانده انبار",
          "ورودی به انبار",
          "توضیحات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
