import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch, useSelector } from "react-redux";
import { liveStockGetFreezingRequests } from "../../services/live-stock-get-freezing-requests";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { DatePicker } from "@mui/x-date-pickers";
import { SPACING } from "../../../../data/spacing";
import {
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Tab,
  Tabs,
  TextField,
} from "@mui/material";
import { formatJustDate } from "../../../../utils/formatTime";
import { LiveStockEnterQuantityWeight } from "../live-stock-enter-quantity-weight/LiveStockEnterQuantityWeight";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { liveStockChangeFreezingState } from "../../services/live-stock-change-freezing-state";
import TuneIcon from "@mui/icons-material/Tune";
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
import CancelOutlinedIcon from "@mui/icons-material/CancelOutlined";

export const LiveStockAllFreezingRequests = () => {
  const dispatch = useDispatch();

  const [value, setValue] = React.useState("0");

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const [tableData, setTableData] = useState([]);
  const [tableDataArchived, setTableDataArchived] = useState([]);
  const [openNotif] = useContext(AppContext);

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

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

  const [actionMenuState, setActionMenuState] = useState({
    anchorPosition: null,
    item: null,
  });

  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]);

  const handleOpenActionMenu = (event, item) => {
    const rect = event.currentTarget.getBoundingClientRect();
    setActionMenuState({
      anchorPosition: {
        top: rect.bottom + window.scrollY,
        left: rect.left + rect.width / 2 + window.scrollX,
      },
      item,
    });
  };

  const handleCloseActionMenu = () => {
    setActionMenuState({
      anchorPosition: null,
      item: null,
    });
  };

  const handleApproveRequest = (item) => {
    if (!item) {
      return;
    }
    dispatch(
      OPEN_MODAL({
        title: "تایید درخواست",
        content: (
          <LiveStockEnterQuantityWeight item={item} fetchApi={fetchApi} />
        ),
      })
    );
    handleCloseActionMenu();
  };

  const handleRejectRequest = (item) => {
    if (!item) {
      return;
    }
    handleCloseActionMenu();
    dispatch(
      liveStockChangeFreezingState({
        allocation_key: item?.key,
        role: getRoleFromUrl(),
        state: "rejected",
      })
    ).then((r) => {
      if (r.payload?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        fetchApi();
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
      handleCloseActionMenu();
    });
  };

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

    const d = freezingRequests
      .filter((item) => item?.state === "pending")
      .map((item, i) => {
        return [
          i + 1,
          item?.coldHouse?.name || "-",
          item?.killHouseRequest?.killHouseRequestInfo?.poultryName || "-",
          item?.killHouseRequest?.killHouseRequestInfo?.killHouseFullname ||
            "-",
          item?.quantity || "-",
          item?.weight || "-",
          formatJustDate(item?.createDate) || "-",
          "در انتظار تایید",
          <Grid container key={i} justifyContent="center">
            <IconButton
              color="primary"
              onClick={(event) => handleOpenActionMenu(event, item)}
            >
              <TuneIcon />
            </IconButton>
          </Grid>,
        ];
      });

    setTableData(d || []);

    const a = freezingRequests
      .filter((item) => item?.state !== "pending")
      .map((item, i) => {
        let state = "تایید شده";
        if (item?.state === "rejected") {
          state = "رد شده";
        }
        return [
          i + 1,
          item?.coldHouse?.name || "-",
          item?.killHouseRequest?.killHouseRequestInfo?.poultryName || "-",
          item?.killHouseRequest?.killHouseRequestInfo?.killHouseFullname ||
            "-",
          item?.quantity || "-",
          item?.weight || "-",
          formatJustDate(item?.createDate) || "-",
          state,
        ];
      });

    setTableDataArchived(a || []);
  }, [freezingRequests]);

  const tableTitle =
    value === "0" ? "تخصیص برای انجماد" : "تخصیص برای انجماد تایید / رد شده";

  const tableFilters = (
    <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>
  );

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={SPACING.SMALL}
    >
      <Tabs
        value={value}
        onChange={handleChange}
        textColor="secondary"
        indicatorColor="secondary"
        aria-label="secondary tabs example"
      >
        <Tab value="0" label="درخواست های جدید" />
        <Tab value="1" label="تائید/ رد شده" />
      </Tabs>

      {value === "0" ? (
        <ResponsiveTable
          title={tableTitle}
          operation={tableFilters}
          columns={[
            "ردیف",
            "سردخانه",
            "مرغدار",
            "کشتارگاه",
            "تعداد",
            "وزن",
            "تاریخ ثبت",
            "وضعیت",
            "عملیات",
          ]}
          data={tableData}
          noPagination
          paginated={false}
        />
      ) : (
        <ResponsiveTable
          title={tableTitle}
          operation={tableFilters}
          columns={[
            "ردیف",
            "سردخانه",
            "مرغدار",
            "کشتارگاه",
            "تعداد",
            "وزن",
            "تاریخ ثبت",
            "وضعیت",
          ]}
          data={tableDataArchived}
          noPagination
          paginated={false}
        />
      )}
      <Popover
        anchorReference="anchorPosition"
        anchorPosition={actionMenuState.anchorPosition || { top: 0, left: 0 }}
        open={Boolean(actionMenuState.anchorPosition)}
        onClose={handleCloseActionMenu}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List sx={{ p: 0 }}>
          <ListItemButton
            onClick={() => handleApproveRequest(actionMenuState.item)}
          >
            <ListItemIcon>
              <CheckCircleOutlineIcon color="success" />
            </ListItemIcon>
            <ListItemText primary="تایید" />
          </ListItemButton>
          <ListItemButton
            onClick={() => handleRejectRequest(actionMenuState.item)}
          >
            <ListItemIcon>
              <CancelOutlinedIcon color="error" />
            </ListItemIcon>
            <ListItemText primary="رد" />
          </ListItemButton>
        </List>
      </Popover>
    </Grid>
  );
};
