import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch, useSelector } from "react-redux";
import { liveStockGetInventoryData } from "../../services/live-stock-get-inventory-data";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { liveStockGetFreezingRequests } from "../../services/live-stock-get-freezing-requests";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { TextField, Typography } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";

export const LiveStockColdHouseComponent = () => {
  const { inventoryData } = useSelector((item) => item.liveStockSlice);
  const [tableData, setTableData] = useState([]);

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(liveStockGetInventoryData());
  }, []);

  const { freezingRequests } = useSelector((state) => state.liveStockSlice);

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

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

  const fetchApi = () => {
    if (!selectedDate1 || !selectedDate2) {
      return;
    }
    dispatch(
      liveStockGetFreezingRequests({
        role: getRoleFromUrl(),
        date1: selectedDate1,
        date2: selectedDate2,
      })
    );
  };

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

  useEffect(() => {
    if (!freezingRequests || !Array.isArray(freezingRequests)) {
      setTableData([]);
      return;
    }

    const d = freezingRequests
      .filter((item) => item?.state === "accepted")
      .map((item, i) => {
        return [
          i + 1,
          item?.coldHouse?.name || "-",
          item?.killHouseRequest?.killHouseRequestInfo?.poultryName || "-",
          item?.killHouseRequest?.killHouseRequestInfo?.killHouseFullname ||
            "-",
          item?.quantity || "-",
          item?.weight || "-",
          formatJustDate(item?.createDate) || "-",
          "در انتظار تایید",
        ];
      });

    setTableData(d || []);
  }, [freezingRequests]);

  const tableTitle = (
    <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
                size={"small"}
                style={{ width: "160px" }}
                {...params}
              />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField
                size={"small"}
                style={{ width: "160px" }}
                {...params}
              />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
      </Grid>
    </Grid>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" mt={2}>
      <SimpleTable
        name={`موجودی انبار ${inventoryData?.name || ""}`}
        columns={["تعداد کل", "وزن کل"]}
        data={[
          [
            inventoryData?.totalQuantity
              ? inventoryData.totalQuantity.toLocaleString()
              : "-",
            inventoryData?.totalWeight
              ? inventoryData.totalWeight.toLocaleString()
              : "-",
          ],
        ]}
      />

      <Grid container mt={4} xs={12}>
        <SimpleTable
          name={tableTitle}
          columns={[
            "ردیف",
            "سردخانه",
            "مرغدار",
            "کشتارگاه",
            "تعداد",
            "وزن",
            "تاریخ ثبت",
            "وضعیت",
          ]}
          data={tableData}
        />
      </Grid>
    </Grid>
  );
};
