import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  Popover,
  TextField,
  Typography,
} from "@mui/material";
import { useDispatch } from "react-redux";
import axios from "axios";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ROUTE_VETFARM_INSPECTIONS } from "../../../../routes/routes";
import { VetFarmSubmitInspectionForm } from "../vet-farm-submit-inspection-form/VetFarmSubmitInspectionForm";
import { useNavigate } from "react-router-dom";
import { AppContext } from "../../../../contexts/AppContext";
import { vetFarmDeleteFarm } from "../../services/vet-farm-delete-farm";
import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined";
import VisibilityIcon from "@mui/icons-material/Visibility";
import PlaylistAddCheckOutlinedIcon from "@mui/icons-material/PlaylistAddCheckOutlined";
import TuneIcon from "@mui/icons-material/Tune";
import { RiSearchLine } from "react-icons/ri";

export const VetFarmSubmitFarmInfo = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [openNotif] = useContext(AppContext);

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `management_vet_farm/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  const VetFarmActions = ({ item, index }) => {
    const [anchorEl, setAnchorEl] = useState(null);

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

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

    const open = Boolean(anchorEl);
    const id = open ? `vet-farm-actions-${item?.key ?? index}` : undefined;

    const handleView = () => {
      handleClose();
      navigate(ROUTE_VETFARM_INSPECTIONS + item.key);
    };

    const handleCreateInspection = () => {
      handleClose();
      dispatch(
        DRAWER({
          right: !(window.innerWidth <= 600),
          bottom: window.innerWidth <= 600,
          title: "ثبت اطلاعات بازرسی",
          content: (
            <VetFarmSubmitInspectionForm
              poultrykey={item.key}
              id={item.poultry.key}
              hall={item.hall}
              updateTable={updateTable}
            />
          ),
        })
      );
    };

    const handleDelete = () => {
      handleClose();
      dispatch(
        OPEN_MODAL({
          title: "سالن را حذف میکنید؟",
          content: (
            <Grid container xs={12} justifyContent="space-around">
              <Grid item container xs={3}>
                <Button
                  fullWidth
                  color="error"
                  variant="contained"
                  onClick={() => {
                    dispatch(LOADING_START());
                    dispatch(vetFarmDeleteFarm(item.key)).then((r) => {
                      updateTable();
                      dispatch(LOADING_END());
                      if (r.error.message.includes("403")) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "برای این فارم قبلا بازرسی ثبت شده است!",
                          severity: "error",
                        });
                      } else {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  بله
                </Button>
              </Grid>
              <Grid item container xs={3}>
                <Button
                  fullWidth
                  variant="outlined"
                  onClick={() => {
                    dispatch(CLOSE_MODAL());
                  }}
                >
                  لغو
                </Button>
              </Grid>
            </Grid>
          ),
        })
      );
    };

    return (
      <>
        <IconButton
          aria-describedby={id}
          color="primary"
          size="small"
          onClick={handleOpen}
        >
          <TuneIcon fontSize="small" />
        </IconButton>
        <Popover
          id={id}
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ p: 1 }}>
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "primary.main" }}
                onClick={handleView}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <VisibilityIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2">نمایش پرونده</Typography>
              </ListItemButton>
            </ListItem>
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "success.main" }}
                onClick={handleCreateInspection}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <PlaylistAddCheckOutlinedIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2">ایجاد بازرسی</Typography>
              </ListItemButton>
            </ListItem>
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "error.main" }}
                onClick={handleDelete}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <DeleteOutlineOutlinedIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2">حذف فارم</Typography>
              </ListItemButton>
            </ListItem>
          </List>
        </Popover>
      </>
    );
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      if (getRoleFromUrl() === "VetFarm") {
        return [
          page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
          item.poultry?.breedingUniqueId
            ? Number(item.poultry.breedingUniqueId)
            : "-",
          item.poultry?.unitName,
          item.poultry?.address?.city?.name,
          item.hall ? item.hall : "ندارد",
          item.inspectionInfo.numberOfInspections
            ? item.inspectionInfo.numberOfInspections
            : 0,
          item?.hatchingQuantity,
          item.vetfarmLosses,
          item.inspectionInfo.numberOfHatching
            ? "%" +
              Math.round(
                (item.vetfarmLosses * 100) /
                  item.inspectionInfo.numberOfHatching
              )
            : 0,
          <VetFarmActions key={item?.key ?? i} item={item} index={i} />,
        ];
      } else {
        return [
          page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
          item.breedingUniqueId ? Number(item.breedingUniqueId) : "-",
          item.unitName,
          item?.address?.city?.name,
          item?.hatchingQuantity?.period
            ? item?.hatchingQuantity?.period
            : "ندارد",
          item?.hatchingQuantity?.totalQuantity?.toLocaleString(),
          item?.hatchingQuantity?.leftOver?.toLocaleString(),
          item?.hatchingQuantity?.unionLosses?.toLocaleString(),
          item?.hatchingQuantity?.vetFarmLosses?.toLocaleString(),
          item?.hatchingQuantity?.totalLosses?.toLocaleString(),
        ];
      }
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    fetchApiData(1);
  }, [dispatch, perPage]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `management_vet_farm/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="start"
      alignItems="center"
      gap={2}
      mt={2}
    >
      <form onSubmit={handleSubmit}>
        <TextField
          id="outlined-basic"
          size="small"
          label="جستجو"
          variant="outlined"
          style={{ width: 250 }}
          onChange={handleTextChange}
        />
        <Button
          // disabled={!textValue}
          type="submit"
          onClick={handleSubmit}
          endIcon={<RiSearchLine />}
        >
          جستجو
        </Button>
      </form>

      <ResponsiveTable
        data={tableData}
        columns={
          getRoleFromUrl() === "VetFarm"
            ? [
                "ردیف",
                "شناسه یکتا فارم",
                "نام فارم",
                "شهر",
                "سالن",
                "تعداد بازرسی",
                "جوجه ریزی",
                "مجموع تلفات (قطعه)",
                "درصد تلفات",
                "عملیات",
              ]
            : [
                "ردیف",
                "شناسه یکتا فارم",
                "نام فارم",
                "شهر",
                "دوره جوجه ریزی",
                "تعداد جوجه ریزی",
                "باقیمانده جوجه ریزی",
                "تلفات اعلامی اتحادیه (قطعه)",
                "تلفات اعلامی دامپزشک فارم (قطعه)",
                "تلفات کل (قطعه)",
              ]
        }
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="سالن های تحت پوشش"
      />
    </Grid>
  );
};
