import {
  IconButton,
  Popover,
  Tooltip,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
} from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
// import DeleteIcon from "@mui/icons-material/Delete";
import ArchiveIcon from "@mui/icons-material/Archive";
import AddIcon from "@mui/icons-material/Add";
import {
  DRAWER,
  OPEN_MODAL,
  LOADING_START,
  LOADING_END,
} from "../../../../lib/redux/slices/appSlice";
import { CityNewKillRequest } from "../city-new-kill-request/CityNewKillRequest";
import { CityArchiveHatchingDrawer } from "../city-archive-hatching-drawer/CityArchiveHatchingDrawer";
import TuneIcon from "@mui/icons-material/Tune";
// import { CityEditHatchingQuantity } from "../city-edit-hatching-quantity/CityEditHatchingQuantity";
import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";
import SmsIcon from "@mui/icons-material/Sms";
import { CitySubmitHatchingReport } from "../city-submit-hatching-report/CitySubmitHatchingReport";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
// import { cityGetHatchingsByAge } from "../../services/city-get-hatchings-by-age";
import EditIcon from "@mui/icons-material/Edit";
import AssignmentReturnedIcon from "@mui/icons-material/AssignmentReturned";
import KeyboardReturnIcon from "@mui/icons-material/KeyboardReturn";
import { archiveHatchingService } from "../../services/archive-hatching";
import { AppContext } from "../../../../contexts/AppContext";
import { CitySubmitLooses } from "../city-submit-looses/CitySubmitLooses";
import PlaylistRemoveIcon from "@mui/icons-material/PlaylistRemove";
import { VetFarmSubmitFarmInfoLosses } from "../../../vet-farm/components/vet-farm-submit-farm-info-losses/VetFarmSubmitFarmInfoLosses";
import InsertPageBreakIcon from "@mui/icons-material/InsertPageBreak";
import { CityManageHatchingRenter } from "../city-manage-hatching-renter/CityManageHatchingRenter";
import PersonAddAlt1Icon from "@mui/icons-material/PersonAddAlt1";
import { cityGetTicketDiffrentClearanceCode } from "../../services/city-get-ticket-different-clearance-code";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
export const CityManageHatchingsOperations = ({
  item,
  selectedAge1,
  selectedAge2,
  updateTable,
  readOnly,
}) => {
  const { userProfile } = useSelector((state) => state.userSlice);
  const dispatch = useDispatch();
  const [anchorEl, setAnchorEl] = useState(null);

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

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

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

  const [openNotif] = useContext(AppContext);

  return (
    <div>
      <IconButton
        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={{ py: 1, minWidth: 200 }}>
          {!readOnly && (
            <>
              <Tooltip title={"ثبت درخواست کشتار"} placement="left-start">
                <ListItemButton
                  onClick={() => {
                    handleClose();
                    dispatch(
                      DRAWER({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        title: "ثبت درخواست کشتار جدید",
                        content: (
                          <CityNewKillRequest
                            selectedAge1={selectedAge1}
                            selectedAge2={selectedAge2}
                            userCheck={item.poultry.userprofile.baseOrder}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  <ListItemIcon sx={{ minWidth: 36, color: "secondary.main" }}>
                    <AddIcon fontSize="small" />
                  </ListItemIcon>
                  <ListItemText
                    primary="ثبت درخواست کشتار"
                    primaryTypographyProps={{ variant: "body2" }}
                  />
                </ListItemButton>
              </Tooltip>

              {item?.InteractTypeName === "مستاجر" && (
                <Tooltip title={"ثبت مستاجر"} placement="left-start">
                  <ListItemButton
                    onClick={() => {
                      handleClose();
                      dispatch(
                        OPEN_MODAL({
                          title: "ثبت مستاجر ",
                          content: (
                            <CityManageHatchingRenter
                              item={item}
                              updateTable={updateTable}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    <ListItemIcon sx={{ minWidth: 36, color: "primary.main" }}>
                      <PersonAddAlt1Icon fontSize="small" />
                    </ListItemIcon>
                    <ListItemText
                      primary="ثبت مستاجر"
                      primaryTypographyProps={{ variant: "body2" }}
                    />
                  </ListItemButton>
                </Tooltip>
              )}

              {(getRoleFromUrl() === "ProvinceOperator" ||
                getRoleFromUrl() === "CityOperator" ||
                getRoleFromUrl() === "CityPoultry" ||
                getRoleFromUrl() === "CityJahad" ||
                getRoleFromUrl() === "CityCommerce" ||
                getRoleFromUrl() === "AdminX" ||
                getRoleFromUrl() === "SuperAdmin") && (
                <Tooltip
                  title={item?.violationReport ? "ویرایش گزارش" : "ثبت گزارش"}
                  placement="left-start"
                >
                  <ListItemButton
                    onClick={() => {
                      handleClose();
                      dispatch(
                        OPEN_MODAL({
                          title: item?.violationReport
                            ? "ویرایش گزارش"
                            : "ثبت گزارش",
                          content: (
                            <CitySubmitHatchingReport
                              updateTable={updateTable}
                              item={item}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    <ListItemIcon sx={{ minWidth: 36, color: "primary.main" }}>
                      <EditIcon fontSize="small" />
                    </ListItemIcon>
                    <ListItemText
                      primary={
                        item?.violationReport ? "ویرایش گزارش" : "ثبت گزارش"
                      }
                      primaryTypographyProps={{ variant: "body2" }}
                    />
                  </ListItemButton>
                </Tooltip>
              )}

              <Tooltip title={"انتقال به بایگانی"} placement="left-start">
                <ListItemButton
                  onClick={() => {
                    handleClose();
                    dispatch(
                      DRAWER({
                        title: "انتقال به آرشیو",
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        content: (
                          <CityArchiveHatchingDrawer
                            selectedAge1={selectedAge1}
                            selectedAge2={selectedAge2}
                            item={item}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  <ListItemIcon sx={{ minWidth: 36, color: "primary.main" }}>
                    <ArchiveIcon fontSize="small" />
                  </ListItemIcon>
                  <ListItemText
                    primary="انتقال به بایگانی"
                    primaryTypographyProps={{ variant: "body2" }}
                  />
                </ListItemButton>
              </Tooltip>

              {(getRoleFromUrl() === "ProvinceOperator" ||
                getRoleFromUrl() === "CityOperator" ||
                getRoleFromUrl() === "AdminX" ||
                getRoleFromUrl() === "SuperAdmin") && (
                <Tooltip title={"ثبت تلفات"} placement="left-start">
                  <ListItemButton
                    onClick={() => {
                      handleClose();
                      dispatch(
                        OPEN_MODAL({
                          title: "ثبت تلفات",
                          content: (
                            <CitySubmitLooses
                              updateTable={updateTable}
                              item={item}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    <ListItemIcon sx={{ minWidth: 36, color: "error.main" }}>
                      <PlaylistRemoveIcon fontSize="small" />
                    </ListItemIcon>
                    <ListItemText
                      primary="ثبت تلفات"
                      primaryTypographyProps={{ variant: "body2" }}
                    />
                  </ListItemButton>
                </Tooltip>
              )}

              <Tooltip
                title={item?.violation ? "بازگشت از تخلف" : "جوجه ریزی متخلف"}
                placement="left-start"
              >
                <ListItemButton
                  onClick={() => {
                    handleClose();
                    dispatch(
                      archiveHatchingService({
                        key: item?.key,
                        violation: item?.violation ? false : true,
                      })
                    ).then((r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "مشکلی پیش آمده است!",
                          severity: "error",
                        });
                      } else {
                        updateTable();
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  <ListItemIcon
                    sx={{
                      minWidth: 36,
                      color: item?.violation ? "primary.main" : "error.main",
                    }}
                  >
                    {item?.violation ? (
                      <KeyboardReturnIcon fontSize="small" />
                    ) : (
                      <AssignmentReturnedIcon fontSize="small" />
                    )}
                  </ListItemIcon>
                  <ListItemText
                    primary={
                      item?.violation ? "بازگشت از تخلف" : "جوجه ریزی متخلف"
                    }
                    primaryTypographyProps={{ variant: "body2" }}
                  />
                </ListItemButton>
              </Tooltip>
            </>
          )}

          {(getRoleFromUrl() === "VetFarm" ||
            getRoleFromUrl() === "CityVet" ||
            getRoleFromUrl() === "VetSupervisor") && (
            <Tooltip title={"ثبت تلفات پایان دوره"} placement="left-start">
              <ListItemButton
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت تلفات پایان دوره",
                      content: (
                        <VetFarmSubmitFarmInfoLosses
                          item={item}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "error.main" }}>
                  <InsertPageBreakIcon fontSize="small" />
                </ListItemIcon>
                <ListItemText
                  primary="ثبت تلفات پایان دوره"
                  primaryTypographyProps={{ variant: "body2" }}
                />
              </ListItemButton>
            </Tooltip>
          )}

          <Tooltip title="خروجی اکسل" placement="left-start">
            <ListItemButton
              component="a"
              href={`${axios.defaults.baseURL}process-for-each-hatching/?key=${item.key}`}
              rel="noreferrer"
            >
              <ListItemIcon sx={{ minWidth: 36, color: "success.main" }}>
                <RiFileExcel2Fill size={18} />
              </ListItemIcon>
              <ListItemText
                primary="خروجی اکسل"
                primaryTypographyProps={{ variant: "body2" }}
              />
            </ListItemButton>
          </Tooltip>

          <Tooltip title="تیکت گزارش کشتار جوجه ریزی" placement="left-start">
            <ListItemButton
              onClick={() => {
                handleClose();
                dispatch(
                  cityGetTicketDiffrentClearanceCode({
                    licence_number: item?.licenceNumber,
                    mobile: userProfile?.mobile,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              <ListItemIcon sx={{ minWidth: 36, color: "error.main" }}>
                <SmsIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText
                primary="تیکت گزارش کشتار"
                primaryTypographyProps={{ variant: "body2" }}
              />
            </ListItemButton>
          </Tooltip>
        </List>
      </Popover>
    </div>
  );
};

export const CityManageHatchingsArchiveActions = ({
  item,
  selectedAge1,
  selectedAge2,
  updateTable,
  readOnly,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [anchorEl, setAnchorEl] = useState(null);

  const open = Boolean(anchorEl);
  const popoverId = open ? "archive-activate-popover" : undefined;

  const handleOpen = (event) => {
    if (readOnly) {
      return;
    }
    setAnchorEl(event.currentTarget);
  };

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

  const handleArchiveClick = () => {
    if (readOnly) {
      return;
    }

    handleClose();
    dispatch(
      DRAWER({
        title: "انتقال به آرشیو",
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        content: (
          <CityArchiveHatchingDrawer
            selectedAge1={selectedAge1}
            selectedAge2={selectedAge2}
            item={item}
            updateTable={updateTable}
          />
        ),
      })
    );
  };

  const handleActivateClick = async () => {
    if (readOnly) {
      return;
    }

    dispatch(LOADING_START());
    try {
      const { data } = await axios.put("poultry_hatching/0/", {
        key: item?.key,
        unknown: false,
      });

      dispatch(LOADING_END());

      if (data?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: data?.error || "فعال‌سازی ناموفق بود.",
          severity: "error",
        });
        return;
      }

      updateTable();
      handleClose();
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "فعال‌سازی با موفقیت انجام شد.",
        severity: "success",
      });
    } catch (error) {
      dispatch(LOADING_END());
      const message =
        error?.response?.data?.result ||
        error?.response?.data?.error ||
        error?.message ||
        "فعال‌سازی ناموفق بود.";
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: message,
        severity: "error",
      });
      handleClose();
    }
  };

  return (
    <>
      <IconButton
        aria-describedby={popoverId}
        color="primary"
        onClick={handleOpen}
        size="small"
        disabled={readOnly}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        id={popoverId}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List sx={{ py: 1, minWidth: 160 }}>
          <ListItemButton onClick={handleArchiveClick} disabled={readOnly}>
            <ListItemIcon sx={{ minWidth: 36, color: "primary.main" }}>
              <ArchiveIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText
              primary="بایگانی"
              primaryTypographyProps={{ variant: "body2" }}
            />
          </ListItemButton>
          <ListItemButton onClick={handleActivateClick} disabled={readOnly}>
            <ListItemIcon sx={{ minWidth: 36, color: "success.main" }}>
              <PlayArrowIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText
              primary="فعال سازی"
              primaryTypographyProps={{ variant: "body2" }}
            />
          </ListItemButton>
        </List>
      </Popover>
    </>
  );
};
