import { useEffect, useState } from "react";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { useDispatch } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import PdfKillRequest from "../province-settlement-pdf-kill-request/ProvinceSettlementPdfKillRequest";

export const ProvinceTradePanelMarketOldRequestDetails = ({ req_key }) => {
  const dispatch = useDispatch();

  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const fetchApiData = async (pageNumber = page) => {
    try {
      dispatch(LOADING_START());
      const response = await axios.get(
        `/market-requests/?role=${getRoleFromUrl()}&search=filter&value=&page=${pageNumber}&page_size=${perPage}&poultry_request_key=${req_key}`
      );
      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      dispatch(LOADING_END());
    }
  };

  const handleUpdate = () => {
    fetchApiData(1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.poultry?.unitName}`,
        `${item?.poultry?.fullname} (${item?.poultry?.mobile})`,
        item?.poultry?.city,
        `${item?.killHouse?.killer === true ? "کشتارکن" : "کشتارگاه"} ${
          item?.killHouse?.name
        }`,
        `${item?.killHouse?.fullname} (${item?.killHouse?.mobile})`,
        item?.killHouse?.city,
        item?.chickenBreed,
        item?.poultryRequest?.killingAge?.toLocaleString(),
        item?.killCapacity?.toLocaleString(),
        formatJustDate(item?.reciveDate),
        formatTime(item?.createDate),
        item?.IndexWeight,
        Math.round(
          item?.IndexWeight * item?.killCapacity || 0
        ).toLocaleString(),
        item?.amount ? item?.amount.toLocaleString() : "0",
        item?.paymentDeadlineDate
          ? formatJustDate(item?.paymentDeadlineDate)
          : "-",
        `${
          item?.marketCodeStatus === true &&
          item?.marketFinalAccept === true &&
          !item?.inputMarketCode &&
          item?.marketState === "pending"
            ? "در انتظار ورود کد احراز"
            : item?.marketFinalAccept === false
            ? "در انتظار تایید خریدار"
            : item?.marketState === "pending"
            ? "در انتظار تایید استان"
            : item?.marketState === "accepted"
            ? "تایید شده"
            : item?.marketState === "rejected"
            ? "رد شده"
            : item?.marketState === "deleted"
            ? "حذف شده"
            : ""
        }`,
        item?.marketState === "accepted" ? (
          <PdfKillRequest pdf_key={item?.key} />
        ) : (
          "-"
        ),
      ];
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    handleUpdate();
  }, [perPage]);

  return (
    <Grid mt={2}>
      <ResponsiveTable
        title={"جزئیات خرید"}
        customWidth="100%"
        data={tableData}
        columns={[
          "ردیف",
          "فارم",
          "مرغدار",
          "شهر",
          "ماهیت خریدار",
          "خریدار",
          "آدرس خریدار",
          "نژاد",
          "سن (روز)",
          "تعداد قطعه",
          "تاریخ کشتار",
          "تاریخ ثبت سفارش",
          "میانگین وزنی (کیلوگرم)",
          "وزن تقریبی (کیلوگرم)",
          "مبلغ هر کیلو (ریال)",
          "حداکثر مهلت تسویه",
          "وضعیت",
          "توافق نامه",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        customColors={[{ rest: true, color: "green" }]}
      />
    </Grid>
  );
};
