import {
  Grid,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
} from "@mui/material";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";

import { useEffect, useState } from "react";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { CitySubmitTenantForm } from "../city-submit-tenant-form/CitySubmitTenantForm";
import { CityEditAvicultureInfoForm } from "../city-edit-aviculture-info-form/CityEditAvicultureInfoForm";
import { cityGetPoultryFarm } from "../../services/city-get-poultry-farms";
import { CityTenantOwnerInfo } from "../city-tenant-owner-info/CityTenantOwnerInfo";
import TuneIcon from "@mui/icons-material/Tune";
import PersonAddAltIcon from "@mui/icons-material/PersonAddAlt";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";

const PoultryFarmActions = ({ item }) => {
  const dispatch = useDispatch();
  const [anchorPosition, setAnchorPosition] = useState(null);

  const hasTenant = Object.keys(item.poultryTenant).length !== 0;

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

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

  const handleAddTenant = () => {
    dispatch(
      DRAWER({
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        title: "ایجاد مستاجر جدید",
        content: <CitySubmitTenantForm id={item.key} />,
      })
    );
    handleClose();
  };

  const handleShowTenantInfo = () => {
    dispatch(
      OPEN_MODAL({
        title: "اطلاعات مستاجر",
        content: <CityTenantOwnerInfo item={item} />,
      })
    );
    handleClose();
  };

  const handleEditInfo = () => {
    dispatch(
      DRAWER({
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        title: "ویرایش اطلاعات مرغدار",
        content: <CityEditAvicultureInfoForm item={item} />,
      })
    );
    handleClose();
  };

  return (
    <Grid container justifyContent="center">
      <IconButton color="primary" size="small" onClick={handleOpen}>
        <TuneIcon />
      </IconButton>
      <Popover
        anchorReference="anchorPosition"
        anchorPosition={anchorPosition || undefined}
        open={Boolean(anchorPosition)}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List sx={{ p: 0 }}>
          {hasTenant ? (
            <ListItemButton onClick={handleShowTenantInfo}>
              <ListItemIcon sx={{ minWidth: 36, color: "info.main" }}>
                <InfoOutlinedIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText
                primary="اطلاعات مستاجر"
                primaryTypographyProps={{
                  variant: "body2",
                  color: "info",
                }}
              />
            </ListItemButton>
          ) : (
            <ListItemButton onClick={handleAddTenant}>
              <ListItemIcon sx={{ minWidth: 36, color: "success.main" }}>
                <PersonAddAltIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText
                primary="افزودن مستاجر"
                primaryTypographyProps={{
                  variant: "body2",
                  color: "success",
                }}
              />
            </ListItemButton>
          )}
          <ListItemButton onClick={handleEditInfo}>
            <ListItemIcon sx={{ minWidth: 36, color: "warning.main" }}>
              <EditOutlinedIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText
              primary="ویرایش اطلاعات"
              primaryTypographyProps={{
                variant: "body2",
                color: "warning",
              }}
            />
          </ListItemButton>
        </List>
      </Popover>
    </Grid>
  );
};

export const CityPoultryFarms = () => {
  const [dataTable, setDataTable] = useState([]);
  const { poultryFarms } = useSelector((state) => state.citySlice);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(cityGetPoultryFarm());
  }, []);

  useEffect(() => {
    const d = poultryFarms
      ?.filter((item) => Object.keys(item.poultryOwner).length === 0)
      .map((item, i) => {
        return [
          i + 1,
          item.unitName,
          item.userprofile.fullName,
          item.userprofile.breedingUniqueId,
          item.address.province.name,
          item.address.city.name,
          item.userprofile.mobile,
          <PoultryFarmActions key={`operation-${item.key}`} item={item} />,
        ];
      });

    setDataTable(d);
  }, [poultryFarms]);

  const [tableDataCol] = useState([
    "ردیف",
    "نام مرغداری",
    "نام صاحب",
    "شناسه یکتا",
    "استان",
    "شهر",
    "تلفن همراه",
    "عملیات",
  ]);

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={SPACING.SMALL}
      mt={SPACING.MEDIUM}
    >
      <ResponsiveTable
        title="مرغداران زیرمجموعه"
        columns={tableDataCol}
        data={dataTable}
        customWidth="100%"
      />
    </Grid>
  );
};
