import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import Table from "../../components/Table/Table";
import { Grid } from "../../components/Grid/Grid";
import { ShowWeight } from "../../components/ShowWeight/ShowWeight";

interface QuotaDashboardByProduct {
  quotas_count: string;
  product_name: string;
  active_quotas_weight: string;
  closed_quotas_weight: string;
  total_quotas_weight: string;
  total_remaining_quotas_weight: string;
  total_remaining_distribution_weight: string;
  received_distribution_weight: string;
  given_distribution_weight: string;
  received_distribution_number: string;
  given_distribution_number: string;
  total_warehouse_entry: string;
  total_sold: string;
}

export const QuotaActivesDashboardDetails = ({
  publicParams,
}: {
  publicParams: any;
}) => {
  const [tableRows, setTableRows] = useState<any[][]>([]);

  const { data: dashboardData } = useApiRequest<QuotaDashboardByProduct[]>({
    api: "/product/web/api/v1/quota/quotas_dashboard_by_product/",
    method: "get",
    queryKey: ["quotasDashboardByProduct"],
    params: publicParams,
  });

  useEffect(() => {
    if (dashboardData && Array.isArray(dashboardData)) {
      const rows = dashboardData.map((item, i) => [
        i + 1,
        item?.product_name,
        parseInt(item?.quotas_count)?.toLocaleString(),
        <ShowWeight key={i} weight={item?.active_quotas_weight} />,
        <ShowWeight key={i} weight={item?.closed_quotas_weight} />,
        <ShowWeight key={i} weight={item?.total_quotas_weight} />,
        <ShowWeight key={i} weight={item?.total_remaining_quotas_weight} />,
        <ShowWeight key={i} weight={item?.received_distribution_weight} />,
        <ShowWeight key={i} weight={item?.given_distribution_weight} />,
        parseInt(item?.received_distribution_number)?.toLocaleString(),
        parseInt(item?.given_distribution_number)?.toLocaleString(),
        <ShowWeight key={i} weight={item?.total_warehouse_entry} />,
        <ShowWeight key={i} weight={item?.total_sold} />,
      ]);
      setTableRows(rows);
    }
  }, [dashboardData]);

  return (
    <Grid container column className="gap-4">
      <Grid>
        <Table
          className="mt-2"
          title="جزئیات سهمیه"
          columns={[
            "ردیف",
            "محصول",
            "تعداد کل سهمیه ها",
            "سهمیه های فعال",
            "سهمیه های بایگانی شده",
            "وزن کل سهمیه ها",
            "باقیمانده وزن سهمیه ها",
            "توزیع دریافتی",
            "توزیع ارسال شده",
            "تعداد توزیع دریافتی",
            "تعداد توزیع ارسالی",
            "کل وزن ورودی به انبار",
            "وزن فروش رفته",
          ]}
          rows={tableRows}
        />
      </Grid>
    </Grid>
  );
};
