import { Card, Grid, IconButton, TextField, Typography } from "@mui/material";
import { ROUTE_SLAUGHTER_FILE } from "../../../../routes/routes";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { SPACING } from "../../../../data/spacing";
import { useFormik } from "formik";
import moment from "moment";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetActiveRequests } from "../../services/slaughter-get-active-requests";
import { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
import { format } from "date-fns-jalali";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";

export const SlaughterActiveRequests = () => {
  const navigate = useNavigate();

  const [dataTable, setDataTable] = useState([]);
  const { slaughterActiveRequests } = useSelector(
    (state) => state.slaughterSlice
  );
  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(slaughterGetActiveRequests({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  useEffect(() => {
    const filteredData = slaughterActiveRequests?.filter(
      (item, i) => item.provinceKillState !== "rejected"
    );
    const key = "orderCode";
    const arrayUniqueByKey = [
      ...new Map(filteredData?.map((item) => [item[key], item])).values(),
    ];
    const d = arrayUniqueByKey.map((item, i) => {
      return [
        i + 1,
        item.orderCode,
        format(new Date(item?.sendDate), "yyyy/MM/dd"),
        item.poultryName,
        item.poultryMobile,
        item.city,
        item.province,
        item.age,
        item.mainQuantity + " قطعه",
        <IconButton
          key={i}
          aria-label="delete"
          color="primary"
          onClick={() => navigate(ROUTE_SLAUGHTER_FILE + item.poultryReqId)}
        >
          <PlagiarismIcon />
        </IconButton>,
      ];
    });

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

  const [tableDataCol] = useState([
    "ردیف",
    "کد سفارش",
    "تاریخ درخواست",
    "مرغدار",
    "تلفن مرغدار",
    "شهر",
    "استان",
    "سن مرغ",
    "تعداد",
    "مشاهده",
  ]);

  const formik = useFormik({
    initialValues: {
      capacity: "",
      recieveTime: "",
      recieveDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
    validationSchema: Yup.object({
      capacity: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      recieveTime: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={SPACING.SMALL}
      mt={SPACING.MEDIUM}
    >
      <Card sx={{ width: "100%" }}>
        <AdvancedTable
          name={
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <Grid>
                <Typography>درخواست های فعال</Typography>
              </Grid>
              <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>
          }
          columns={tableDataCol}
          data={dataTable}
        />
      </Card>
    </Grid>
  );
};
