import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Typography,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import { Grid } from "../../../../components/grid/Grid";
import { useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ROUTE_SLAUGHTER_FILE } from "../../../../routes/routes";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
import SettingsBackupRestoreIcon from "@mui/icons-material/SettingsBackupRestore";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import { slaughterDeleteAllocatedBackRequestService } from "../../services/slaughter-delete-allocated-back-kill-request";
import { slaughterRemoveAllocateCarService } from "../../services/slaughter-remove-allocate-car";
import { slaughterGetActiveRequests } from "../../services/slaughter-get-active-requests";
import { slaughterGetAllocatedCarsService } from "../../services/slaughter-get-allocated-cars";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch, useSelector } from "react-redux";
import {
  OPEN_MODAL,
  CLOSE_MODAL,
  DRAWER,
} from "../../../../lib/redux/slices/appSlice";
import { SlaughterEditAllocatedCar } from "../slaughter-edit-allocated-car/SlaughterEditAllocatedCar";
import { SlaughterSubmitChickenPrice } from "../slaughter-submit-chicken-price/SlaughterSubmitChickenPrice";
import SlaughterAssignCar from "../../../file/components/slaughter-assign-car/SlaughterAssignCar";
import { SPACING } from "../../../../data/spacing";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterAllocatedCarToRequestOperation = ({
  item,
  updateTable,
  isAllocatedCar = false,
  selectedDate1,
  selectedDate2,
  submitStatus,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const [openNotif, , contextDate1, , contextDate2] = useContext(AppContext);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  // Use prop dates if provided, otherwise use context dates
  const date1 = selectedDate1 || contextDate1;
  const date2 = selectedDate2 || contextDate2;

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };
  const navigate = useNavigate();

  const open = Boolean(anchorEl);
  const id = open ? "popover" : undefined;

  const confirmDeleteAllocatedCar = () => {
    dispatch(slaughterRemoveAllocateCarService(item.killHouseRequestKey)).then(
      (r) => {
        if (r.payload?.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          dispatch(CLOSE_MODAL());
          // Refresh both tables
          dispatch(
            slaughterGetActiveRequests({
              isCar: true,
              selectedDate1: date1,
              selectedDate2: date2,
              role_key: checkPathStartsWith("slaughter")
                ? selectedSubUser?.key || ""
                : "",
            })
          );
          dispatch(
            slaughterGetAllocatedCarsService({
              selectedDate1: date1,
              selectedDate2: date2,
              role_key: checkPathStartsWith("slaughter")
                ? selectedSubUser?.key || ""
                : "",
            })
          );
          if (updateTable) updateTable();
        }
      }
    );
  };

  const handleDeleteAllocatedCar = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "تایید حذف",
        content: (
          <Grid
            container
            direction="column"
            gap={SPACING.SMALL}
            sx={{ p: 2, minWidth: "300px" }}
          >
            <Typography variant="body1">
              آیا از حذف تخصیص این خودرو اطمینان دارید؟
            </Typography>
            <Grid
              container
              gap={SPACING.SMALL}
              justifyContent="space-between"
              xs={12}
            >
              <Button
                variant="outlined"
                color="secondary"
                onClick={() => dispatch(CLOSE_MODAL())}
              >
                انصراف
              </Button>
              <Button
                variant="contained"
                color="error"
                onClick={confirmDeleteAllocatedCar}
              >
                حذف
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

  const handleEditAllocatedCar = () => {
    dispatch(
      OPEN_MODAL({
        title: "ویرایش خودرو و کد حمل",
        content: (
          <SlaughterEditAllocatedCar
            item={item}
            updateTable={() => {
              // Refresh both tables
              dispatch(
                slaughterGetActiveRequests({
                  isCar: true,
                  selectedDate1: date1,
                  selectedDate2: date2,
                  role_key: checkPathStartsWith("slaughter")
                    ? selectedSubUser?.key || ""
                    : "",
                })
              );
              dispatch(
                slaughterGetAllocatedCarsService({
                  selectedDate1: date1,
                  selectedDate2: date2,
                  role_key: checkPathStartsWith("slaughter")
                    ? selectedSubUser?.key || ""
                    : "",
                })
              );
              if (updateTable) updateTable();
            }}
            poultryRequestKey={item?.poultryReqKey}
            killHouseKey={item?.killHouseKey}
            killRequestKey={item?.killRequestKey}
          />
        ),
      })
    );
    handleClose();
  };

  const handleViewFile = () => {
    navigate(ROUTE_SLAUGHTER_FILE + item.poultryReqId);
  };

  const handleReturnAllocation = () => {
    dispatch(
      slaughterDeleteAllocatedBackRequestService({
        provinceKillRequestKey: item?.provinceKillRequestKey,
        returnAllocationQuantity: true,
      })
    ).then((r) => {
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.error,
          severity: "error",
        });
      } else {
        if (updateTable) {
          updateTable();
        }
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات برگشت تخصیص با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const handleRegisterCar = () => {
    if (submitStatus === true && item?.killHousePrice === 0) {
      dispatch(
        OPEN_MODAL({
          title: "ثبت قیمت مرغ زنده",
          content: (
            <SlaughterSubmitChickenPrice item={item} fetchData={updateTable} />
          ),
        })
      );
    } else {
      dispatch(
        DRAWER({
          title: "انجام عملیات تخصیص",
          top: !(window.innerWidth <= 600),
          bottom: window.innerWidth <= 600,
          content: (
            <SlaughterAssignCar
              indexWeight={item.indexWeight}
              killHouseName={item.killHouseName}
              killHouseCheckKey={item.killHouseCheckKey}
              killHouseKey={item.killHouseKey}
              killRequestKey={item.killRequestKey}
              poultryRequestKey={item.poultryReqKey}
              provinceAllocationLimit={item.remainQuantity || 0}
              item={item}
            />
          ),
        })
      );
    }
  };

  const options = [];

  if (!isAllocatedCar) {
    const needsPrice =
      submitStatus === true && (item?.killHousePrice || 0) === 0;

    options.push({
      key: "register",
      label: "ثبت خودرو",
      color: needsPrice ? "error.main" : "primary.main",
      icon: AddCircleOutlineIcon,
      action: handleRegisterCar,
    });

    options.push({
      key: "viewFile",
      label: "مشاهده پرونده",
      color: "primary.main",
      icon: PlagiarismIcon,
      action: handleViewFile,
    });

    const returnDisabled = item?.allocatedQuantity > 0;
    options.push({
      key: "return",
      label: "برگشت تخصیص",
      color: returnDisabled ? "text.disabled" : "warning.main",
      icon: SettingsBackupRestoreIcon,
      action: handleReturnAllocation,
      disabled: returnDisabled,
    });
  }

  if (isAllocatedCar) {
    options.push({
      key: "editAllocated",
      label: "ویرایش خودرو و کد حمل",
      color: "info.main",
      icon: EditIcon,
      action: handleEditAllocatedCar,
    });

    options.push({
      key: "deleteAllocated",
      label: "حذف تخصیص خودرو",
      color: "error.main",
      icon: DeleteIcon,
      action: handleDeleteAllocatedCar,
    });
  }

  const handleOptionClick = (option) => {
    if (option.disabled) {
      return;
    }
    handleClose();
    option.action();
  };

  return (
    <Grid container>
      <IconButton
        size="small"
        aria-describedby={id}
        variant="contained"
        color="primary"
        onClick={handleClick}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
      >
        <List sx={{ minWidth: 150, p: 0.5 }}>
          {options.map((option) => {
            const IconComponent = option.icon;
            const itemColor = option.disabled ? "text.disabled" : option.color;
            return (
              <ListItemButton
                key={option.key}
                disabled={option.disabled}
                onClick={() => handleOptionClick(option)}
                sx={{
                  borderRadius: 1,
                  mb: 0.25,
                  py: 0.5,
                  "&:last-of-type": {
                    mb: 0,
                  },
                }}
              >
                <ListItemIcon sx={{ color: itemColor, minWidth: 32 }}>
                  <IconComponent fontSize="small" />
                </ListItemIcon>
                <ListItemText
                  primary={option.label}
                  primaryTypographyProps={{
                    sx: {
                      color: itemColor,
                      fontSize: "0.82rem",
                      fontWeight: 600,
                    },
                  }}
                />
              </ListItemButton>
            );
          })}
        </List>
      </Popover>
    </Grid>
  );
};
