import { Card, IconButton, TextField, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { AdvancedTable } from "../advanced-table/AdvancedTable";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
import { useDispatch, useSelector } from "react-redux";
import { getRequestsAwaitingPayment } from "./service";
import { format } from "date-fns-jalali";
import { SPACING } from "../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { AppContext } from "../../contexts/AppContext";
import { Grid } from "../grid/Grid";

export const RequestsAwaitingPayment = () => {
  const { awaitingPaymentRequests } = useSelector(
    (state) => state.generalSlice
  );

  const navigate = useNavigate();
  const [dataTable, setDataTable] = useState([]);
  const urlRole = window.location.pathname.split("/")[1];

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getRequestsAwaitingPayment({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  useEffect(() => {
    const fileUrl = "/" + urlRole + "/file/";

    const d = awaitingPaymentRequests?.map((item, i) => {
      return [
        i + 1,
        item.provinceCheckInfo?.killHouseAssignment?.killHouseRequest?.barCode,
        format(new Date(item?.poultryRequest?.sendDate), "yyyy/MM/dd"),
        format(new Date(item?.factorDate), "yyyy/MM/dd"),
        item?.poultryRequest?.poultryName,
        item.provinceCheckInfo?.killHouseAssignment?.killHouseRequest
          ?.killRequest?.killHouse.name,
        item.provinceCheckInfo.killHouseAssignment.netWeight.toLocaleString() +
          " کیلوگرم",
        item.provinceCheckInfo?.killHouseAssignment?.realQuantity.toLocaleString() +
          " قطعه",
        item.totalPrice.toLocaleString() + " ﷼",
        <IconButton
          key={i}
          aria-label="delete"
          color="primary"
          onClick={() =>
            navigate(fileUrl + item?.poultryRequest?.poultryRequestId)
          }
        >
          <PlagiarismIcon />
        </IconButton>,
      ];
    });

    setDataTable(d);
  }, [awaitingPaymentRequests]);

  return (
    <Card>
      <AdvancedTable
        name={
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <Grid container gap={SPACING.TINY}>
              <Typography>درخواست های در انتظار پرداخت</Typography>
            </Grid>
            <Grid container gap={SPACING.SMALL}>
              <Grid>
                <DatePicker
                  label="از تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate1}
                  onChange={(e) => {
                    setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
              <Grid>
                <DatePicker
                  label="تا تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate2}
                  onChange={(e) => {
                    setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
            </Grid>
          </Grid>
        }
        columns={[
          "ردیف",
          "بارکد",
          "تاریخ کشتار",
          "تاریخ صدور فاکتور",
          "مرغدار",
          "کشتارگاه",
          "وزن",
          "تعداد",
          "مبلغ کل فاکتور",
          "مشاهده",
        ]}
        data={dataTable}
      />
    </Card>
  );
};
