import { useEffect, useState } from "react";
import Table from "../components/Table/Table";
import { Grid } from "../components/Grid/Grid";
import { useApiRequest } from "../utils/useApiRequest";
import { formatJustDate, formatJustTime } from "../utils/formatTime";
import { TableButton } from "../components/TableButton/TableButton";
import { useModalStore } from "../context/zustand-store/appStore";
import TransactionDetails from "../partials/transactions/TransactionDetails";
import { DashboardResponse, ProductSummaryItem } from "../types/transactions";
import { ProductSummaryModal } from "../partials/transactions/ProductSummaryModal";
import { PaginationParameters } from "../components/PaginationParameters/PaginationParameters";
import TransactionSharingDetails from "../partials/transactions/TransactionSharingDetails";
import { convertNumberToPersian } from "../utils/convertNumberToPersian";

type TransactionResponse = {
  results?: any[];
  count?: number;
};

export default function Transactions() {
  const [params, setParams] = useState({ page: 1, page_size: 10 });

  const [publicParams, setPublicParams] = useState({
    start: null,
    end: null,
    search: null,
    status: "success",
  });
  const { openModal } = useModalStore();

  const [tableData, setTableData] = useState<any[]>([]);

  const { data, refetch: refetchTransactions } =
    useApiRequest<TransactionResponse>({
      api: "/warehouse/web/api/v1/inventory_sale_transaction/",
      params: { ...params, ...publicParams },
      queryKey: ["transactions", params],
    });

  const { data: DashboardData, refetch: refetchDashboard } =
    useApiRequest<DashboardResponse>({
      api: `/warehouse/web/api/v1/inventory_sale_transaction/transactions_dashboard/`,
      params: { ...publicParams },
      queryKey: ["distributions_dashboard"],
    });

  const productSummary: ProductSummaryItem[] =
    DashboardData?.product_summary || [];
  const hasProductSummary = productSummary.length > 0;

  const handleOpenProductSummaryModal = () => {
    if (!hasProductSummary) return;

    openModal({
      title: "آمار محصولات",
      content: <ProductSummaryModal products={productSummary} />,
      isFullSize: true,
    });
  };

  const handleUpdate = () => {
    refetchTransactions();
    refetchDashboard();
  };

  useEffect(() => {
    if (data?.results) {
      const formatted = data.results.map((item: any, i: number) => {
        const items = item?.items || [];
        const quotaSaleUnits = items
          .map((p: any) => p?.quota_sale_unit)
          .filter((unit: any) => unit);
        const totalWeight = items.reduce(
          (sum: number, p: any) => sum + (p?.weight || 0),
          0
        );

        let weightNature;
        if (quotaSaleUnits.length > 0) {
          const allEqual =
            items.length > 0 &&
            quotaSaleUnits.length === items.length &&
            new Set(quotaSaleUnits).size === 1;
          weightNature = allEqual
            ? `${totalWeight.toLocaleString()} ${quotaSaleUnits[0] || ""}`
            : "ترکیبی";
        } else {
          weightNature = `${totalWeight.toLocaleString()} کیلوگرم`;
        }

        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.seller_organization?.name || "-",
          item?.rancher_fullname || "آزاد",
          item?.rancher?.national_code || "-",
          <Grid container column key={i}>
            <Grid>{formatJustDate(item?.transaction_date) || "-"}</Grid>
            <Grid>{formatJustTime(item?.transaction_date) || "-"}</Grid>
          </Grid>,
          item?.items?.map((p: any) => `${p?.name}`).join(" - ") || "-",
          item?.transaction_id || "-",
          item?.pos_device?.serial || "-",
          item?.payer_cart || "-",
          item?.product_type === "gov" ? "دولتی" : "آزاد",
          item?.price_paid?.toLocaleString() ||
            item?.transaction_price?.toLocaleString() ||
            "-",
          weightNature,
          item?.transaction_status === "waiting"
            ? "درحال انتظار"
            : item?.transaction_status === "success"
            ? "موفق"
            : item?.transaction_status === "failed"
            ? `ناموفق ( ${item?.result_text || "-"} ${
                item?.transaction_status_code || ""
              } )`
            : "-",
          <TableButton
            size="small"
            key={i}
            onClick={() => {
              openModal({
                title: "جزئیات تراکنش",
                content: (
                  <TransactionDetails
                    transaction={item}
                    items={item?.items || []}
                  />
                ),
                isFullSize: true,
              });
            }}
          />,
        ];
      });
      setTableData(formatted);
    } else {
      setTableData([]);
    }
  }, [data, params.page, params.page_size]);

  return (
    <Grid container column className="gap-4">
      <PaginationParameters
        excelInfo={{
          link: `/warehouse/excel/inventory_sale_transaction_excel/?status=${
            publicParams.status
          }&start=${publicParams.start || ""}&end=${
            publicParams.end || ""
          }&search=${publicParams.search || ""}`,
          title: "لیست تراکنش ها",
        }}
        getData={handleUpdate}
        title="فیلتر تراکنش"
        onChange={(r) => {
          setPublicParams((prev) => ({ ...prev, ...(r as any) }));
          setParams((prev) => ({ ...prev, page: 1 }));
        }}
        filters={[
          {
            key: "status",
            data: [
              { key: "", value: "همه" },
              { key: "success", value: "موفق" },
              { key: "failed", value: "ناموفق" },
              { key: "waiting", value: "درحال انتظار" },
            ],
            selectedKeys: [publicParams.status],
            onChange: (keys) => {
              setPublicParams((prev) => ({
                ...prev,
                status: keys[0] as string,
              }));
              setParams((prev) => ({ ...prev, page: 1 }));
            },
            title: "وضعیت",
            size: "small",
          },
        ]}
      />
      <Grid container column isDashboard>
        <Table
          isDashboard
          noPagination
          noSearch
          title="خلاصه تراکنش ها"
          columns={[
            "تعداد کل تراکنش‌ها",
            "تراکنش‌های موفق",
            "تراکنش‌های ناموفق",
            "تراکنش‌های در انتظار",
            "مجموع مبلغ (ریال)",
            "مبلغ به حروف (ریال)",
            "مجموع وزن (کیلوگرم)",
            "جزئیات محصولات",
            "جزئیات تسهیم",
          ]}
          rows={[
            [
              DashboardData?.transaction_summary?.total_transactions?.toLocaleString() ||
                0,
              DashboardData?.transaction_summary?.success_transactions?.toLocaleString() ||
                0,
              DashboardData?.transaction_summary?.failed_transactions?.toLocaleString() ||
                0,
              DashboardData?.transaction_summary?.waiting_transactions?.toLocaleString() ||
                0,
              DashboardData?.transaction_summary?.total_amount?.toLocaleString() ||
                0,
              convertNumberToPersian(
                DashboardData?.transaction_summary?.total_amount || 0
              ),
              DashboardData?.transaction_summary?.total_weight?.toLocaleString() ||
                0,
              <TableButton
                size="small"
                key={DashboardData?.product_summary?.length}
                disabled={!hasProductSummary}
                onClick={handleOpenProductSummaryModal}
              />,
              <TableButton
                size="small"
                key={DashboardData?.product_summary?.length}
                onClick={() => {
                  openModal({
                    title: "جزئیات تسهیم",
                    content: (
                      <TransactionSharingDetails
                        data={DashboardData?.brokers_sharing_summary}
                      />
                    ),
                    isFullSize: true,
                  });
                }}
              />,
            ],
          ]}
        />
      </Grid>

      <Grid className="w-full">
        <Table
          onChange={setParams}
          count={data?.count || 0}
          isPaginated
          noSearch
          title="لیست تراکنش ها"
          columns={[
            "ردیف",
            "تعاونی",
            "دامدار",
            "کد ملی دامدار",
            "تاریخ",
            "محصولات",
            "شناسه تراکنش",
            "سریال دستگاه",
            "شماره کارت",
            "نوع فروش",
            "مبلغ",
            "ماهیت وزن",
            "وضعیت",
            "جزئیات تراکنش",
          ]}
          rows={tableData}
        />
      </Grid>
    </Grid>
  );
}
