import { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { TradepanelDetails } from "../trade-panel-details/TradepanelDetails";
import { TradePanelPurchaseOperation } from "../trade-panel-purchase-operation/TradePanelPurchaseOperation";
import { TradePanelFilters } from "../trade-panel-filter/TradePanelFilter";
import { CHICKEN_BREEDS } from "./constants";

export const TradePanelTable = ({
  data,
  page,
  perPage,
  totalRows,
  filters,
  cities,
  onFilterUpdate,
  onCityChange,
  onBreedChange,
  onPriceFilterSubmit,
  onAgeFilterSubmit,
  onPageChange,
  onPerRowsChange,
  updateTable,
}) => {
  const [tableData, setTableData] = useState([]);

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }

    const formatNumber = (num) => {
      if (num === null || num === undefined) return "0";
      return num.toLocaleString();
    };

    const rowNumber = (index) => {
      const currentPage = page || 1;
      const currentPerPage = perPage || 20;
      return currentPage === 1
        ? index + 1
        : index + currentPerPage * (currentPage - 1) + 1;
    };

    const tableRows = data.map((item, i) => [
      rowNumber(i),
      <TradepanelDetails key={i} details_key={item?.age?.hatchingKey || ""} />,
      `${item?.poultry?.fullname || ""} (${item?.poultry?.mobile || ""})`,
      item?.poultry?.city || "-",
      item?.chickenBreed || "-",
      item?.age?.age || "-",
      item?.IndexWeight || "-",
      item?.sendDate ? formatJustDate(item.sendDate) : "-",
      item?.quantity || "-",
      formatNumber(item?.remainQuantity),
      formatNumber(item?.totalAllocated),
      formatNumber(item?.amount),
      <TradePanelPurchaseOperation
        key={i}
        item={item}
        updateTable={updateTable}
      />,
    ]);

    setTableData(tableRows);
  }, [data, page, perPage, updateTable]);

  const columns = [
    "ردیف",
    "جزئیات",
    "نام و نام خانوادگی (تلفن)",
    "استان / شهر",
    "نژاد",
    "سن جوجه",
    "میانگین وزنی (کیلوگرم) ",
    "تاریخ کشتار",
    "تعداد قطعه",
    "مانده قابل خرید",
    "فروش رفته ",
    "مبلغ هر کیلو (ریال)",
    ...(getRoleFromUrl() === "KillHouse" ? ["خرید"] : []),
  ];

  return (
    <Grid container spacing={2} sx={{ width: "100%" }}>
      <Grid item xs={12} md={2}>
        <TradePanelFilters
          filters={filters}
          updateFilter={onFilterUpdate}
          handleCityChange={onCityChange}
          handleBreedChange={onBreedChange}
          handlePriceFilterSubmit={onPriceFilterSubmit}
          handleAgeFilterSubmit={onAgeFilterSubmit}
          cities={cities}
          chickenBreeds={CHICKEN_BREEDS}
        />
      </Grid>

      <Grid item xs={12} md={10}>
        <ResponsiveTable
          title="لیست اعلام کشتار های مرغداران"
          data={tableData}
          customWidth="100%"
          columns={columns}
          handlePageChange={onPageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={onPerRowsChange}
        />
      </Grid>
    </Grid>
  );
};
