import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import { TradepanelDetails } from "../trade-panel-details/TradepanelDetails";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { DatePicker } from "@mui/x-date-pickers";
import { IconButton, TextField } from "@mui/material";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";
import { ProvinceTradePanelMarketOldRequestDetails } from "../province-trade-panel-market-old-request-details/ProvinceTradePanelMarketOldRequestDetails";

export const ProvinceTradePanelOldRequests = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(20);
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const fetchApiData = async (pageNumber = page) => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `direct-buying-poultry-requests?page=${pageNumber}&page_size=${perPage}&date1=${selectedDate1}&date2=${selectedDate2}`
      );

      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      dispatch(LOADING_END());
    }
  };

  useEffect(() => {
    fetchApiData(1);
  }, [perPage, selectedDate1, selectedDate2]);

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <TradepanelDetails key={i} details_key={item?.age?.hatchingKey} />,
        `${item?.poultry?.fullname} (${item?.poultry?.mobile})`,
        item?.poultry?.city,
        item?.chickenBreed,
        item?.age?.age,
        item?.IndexWeight,
        formatJustDate(item?.sendDate),
        item?.quantity,
        item?.remainQuantity ? item?.remainQuantity.toLocaleString() : "0",
        item?.totalAllocated ? item?.totalAllocated?.toLocaleString() : "0",
        item?.amount ? item?.amount.toLocaleString() : "0",
        <IconButton
          key={i}
          color="primary"
          onClick={() => {
            dispatch(
              DRAWER({
                top: true,
                title: "جزئیات خرید",
                content: (
                  <ProvinceTradePanelMarketOldRequestDetails
                    req_key={item?.key}
                  />
                ),
              })
            );
          }}
        >
          <RemoveRedEyeIcon />
        </IconButton>,
      ];
    });

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

  return (
    <Grid item xs={12} mt={2}>
      <Grid container xs={12} justifyConter="start" gap={1}>
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} size="small" {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} size="small" {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
      </Grid>
      <ResponsiveTable
        title="لیست اعلام کشتار های مرغداران"
        data={tableData}
        customWidth="100%"
        columns={[
          "ردیف",
          "جزئیات",
          "نام و نام خانوادگی (تلفن)",
          "استان / شهر",
          "نژاد",
          "سن جوجه",
          "میانگین وزنی (کیلوگرم) ",
          "تاریخ کشتار",
          "تعداد قطعه",
          "مانده قابل خرید",
          "فروش رفته ",
          "مبلغ هر کیلو (ریال)",
          "جزئیات خرید",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
      />
    </Grid>
  );
};
