import {
  IconButton,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Typography,
} from "@mui/material";
import { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import TuneIcon from "@mui/icons-material/Tune";
import { useDispatch, useSelector } from "react-redux";
import { hatchingUndoArchiveService } from "../../services/hatching-undo-archive";
import { AppContext } from "../../../../contexts/AppContext";
import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { CitySubmitHatchingReport } from "../city-submit-hatching-report/CitySubmitHatchingReport";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import InsertPageBreakIcon from "@mui/icons-material/InsertPageBreak";
import { VetFarmSubmitFarmInfoLosses } from "../../../vet-farm/components/vet-farm-submit-farm-info-losses/VetFarmSubmitFarmInfoLosses";
import AddIcon from "@mui/icons-material/Add";
import KeyboardReturnIcon from "@mui/icons-material/KeyboardReturn";
import SmsIcon from "@mui/icons-material/Sms";
import { cityGetTicketDiffrentClearanceCode } from "../../services/city-get-ticket-different-clearance-code";
export const CityHatchingsArchiveOperations = ({
  item,
  updateArchive,
  readOnly,
}) => {
  const { userProfile } = useSelector((state) => state.userSlice);
  const dispatch = useDispatch();
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);
  const [openNotif] = useContext(AppContext);
  const role = getRoleFromUrl();

  const openPopover = (event) => {
    setPopoverOpen(true);
    setAnchorEl(event.currentTarget);
  };

  const closePopover = () => {
    setPopoverOpen(false);
    setAnchorEl(null);
  };

  const handleUndoArchive = () => {
    closePopover();
    dispatch(
      hatchingUndoArchiveService({
        key: item.key,
        type: "return_archive",
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        updateArchive(1);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const handleOpenReportModal = () => {
    closePopover();
    dispatch(
      OPEN_MODAL({
        title: "ثبت گزارش",
        content: (
          <CitySubmitHatchingReport
            updateTable={updateArchive}
            item={item}
            isArchive
          />
        ),
      })
    );
  };

  const handleOpenLossesModal = () => {
    closePopover();
    dispatch(
      OPEN_MODAL({
        title: "ثبت تلفات پایان دوره",
        content: (
          <VetFarmSubmitFarmInfoLosses
            item={item}
            updateTable={updateArchive}
          />
        ),
      })
    );
  };

  const handleExcelExport = () => {
    closePopover();
    const url = `${axios.defaults.baseURL}process-for-each-hatching/?key=${item.key}`;
    window.open(url, "_blank");
  };

  const handleCreateTicket = () => {
    closePopover();
    dispatch(
      cityGetTicketDiffrentClearanceCode({
        licence_number: item?.licenceNumber,
        mobile: userProfile?.mobile,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی پیش آمده است!",
          severity: "error",
        });
      } else {
        updateArchive(1);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const provinceAndAdminRoles = [
    "ProvinceOperator",
    "CityOperator",
    "AdminX",
    "SuperAdmin",
  ];
  const vetRoles = ["VetFarm", "CityVet", "VetSupervisor"];

  const options = [
    !readOnly && {
      key: "undo",
      label: "بازگشت جوجه ریزی",
      color: "primary.main",
      icon: <KeyboardReturnIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleUndoArchive,
    },
    provinceAndAdminRoles.includes(role) && {
      key: "report",
      label: "ثبت گزارش",
      color: "secondary.main",
      icon: <AddIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleOpenReportModal,
    },
    vetRoles.includes(role) && {
      key: "losses",
      label: "ثبت تلفات پایان دوره",
      color: "error.main",
      icon: <InsertPageBreakIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleOpenLossesModal,
    },
    {
      key: "excel",
      label: "خروجی اکسل",
      color: "success.main",
      icon: <RiFileExcel2Fill size={18} style={{ color: "inherit" }} />,
      action: handleExcelExport,
    },
    {
      key: "ticket",
      label: "تیکت گزارش کشتار جوجه ریزی",
      color: "error.main",
      icon: <SmsIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleCreateTicket,
    },
  ].filter(Boolean);

  return (
    <Grid>
      <IconButton variant="contained" color="primary" onClick={openPopover}>
        <TuneIcon />
      </IconButton>
      <Popover
        open={popoverOpen}
        anchorEl={anchorEl}
        onClose={closePopover}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List sx={{ width: 200, p: 1 }}>
          {options.map((option) => (
            <ListItemButton
              key={option.key}
              onClick={() => {
                if (option.disabled) {
                  return;
                }
                option.action();
              }}
              disabled={Boolean(option.disabled)}
              sx={{
                borderRadius: 1,
                mb: 0.5,
                color: option.disabled ? "text.disabled" : option.color,
                "&:last-of-type": {
                  mb: 0,
                },
              }}
            >
              <ListItemIcon
                sx={{
                  color: option.disabled ? "text.disabled" : option.color,
                  minWidth: 36,
                }}
              >
                {option.icon}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography
                    sx={{
                      color: option.disabled ? "text.disabled" : option.color,
                      fontWeight: 600,
                      fontSize: { xs: "13px", md: "14px" },
                    }}
                  >
                    {option.label}
                  </Typography>
                }
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </Grid>
  );
};
