import { Grid, IconButton, TextField } from "@mui/material";
import { ROUTE_SLAUGHTER_FILE } from "../../../../routes/routes";
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 EditIcon from "@mui/icons-material/Edit";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import SlaughterCheckRequest from "../../../file/components/slaughter-check-request/SlaughterCheckRequest";
import { format } from "date-fns-jalali";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterAllocatedCheckRequests = () => {
  const navigate = useNavigate();
  const [dataTable, setDataTable] = useState([]);
  const { slaughterActiveRequests } = useSelector(
    (state) => state.slaughterSlice
  );
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

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

  useEffect(() => {
    dispatch(
      slaughterGetActiveRequests({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
  }, [selectedDate1, selectedDate2, selectedSubUser?.key]);

  useEffect(() => {
    const filteredData = slaughterActiveRequests?.filter(
      (item) => item.provinceKillState === "pending"
    );
    // const key = "orderCode";
    // const arrayUniqueByKey = [
    //   ...new Map(filteredData?.map((item) => [item[key], item])).values(),
    // ];
    const d = filteredData?.map((item, i) => {
      return [
        i + 1,
        item.orderCode,
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        item?.freeSaleInProvince === false ? "دولتی" : "آزاد",
        format(new Date(item?.sendDate), "yyyy/MM/dd"),
        `${item.poultryName} (${item.poultryMobile})`,
        `${item.killHouseName} (${item.killHouseMobile})`,
        item.city,
        item.province,
        item.age,
        item.mainQuantity.toLocaleString() + " قطعه",
        item.amount.toLocaleString() + " ﷼",
        item.chickenBreed,
        item.indexWeight + " کیلوگرم",
        <IconButton
          key={i}
          color="primary"
          onClick={() => {
            dispatch(
              DRAWER({
                title: "انجام عملیات تخصیص",
                // right: !(window.innerWidth <= 600),
                top: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: <SlaughterCheckRequest item={item} i={i} />,
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>,
        <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 direction="column" gap={SPACING.SMALL} mt={SPACING.MEDIUM}>
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <DatePicker
          label="از تاریخ"
          id="date"
          renderInput={(params) => (
            <TextField style={{ width: "160px" }} {...params} />
          )}
          value={selectedDate1}
          onChange={(e) => {
            setSelectedDate1(moment(e).format("YYYY-MM-DD"));
          }}
        />
        <DatePicker
          label="تا تاریخ"
          id="date"
          renderInput={(params) => (
            <TextField style={{ width: "160px" }} {...params} />
          )}
          value={selectedDate2}
          onChange={(e) => {
            setSelectedDate2(moment(e).format("YYYY-MM-DD"));
          }}
        />
      </Grid>

      <ResponsiveTable
        title={"درخواست های در انتظار تایید"}
        columns={tableDataCol}
        data={dataTable}
        paginated
      />
    </Grid>
  );
};
