import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { EditPoultryCity } from "../edit-poultry-city/EditPoultryCity";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { RiFileExcel2Fill } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provinceGetDashboardPoultriesService } from "../../services/getDashboardOfManagePoultries";
import { getPoultryActiveLimitedService } from "../../services/province-get-poultry-active-limited";
import Chip from "@mui/material/Chip";
import TuneIcon from "@mui/icons-material/Tune";
import ManageAccountsIcon from "@mui/icons-material/ManageAccounts";
import FileDownloadIcon from "@mui/icons-material/FileDownload";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import ToggleOffIcon from "@mui/icons-material/ToggleOff";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const ManagePoultries = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const userKey = useSelector((state) => state.userSlice?.userProfile?.key);
  const [dashboardData, setDashboardData] = useState([]);
  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 [has500Error, setHas500Error] = useState(false);

  const PoultryActions = ({ poultryItem, onToggleLimit }) => {
    const navigate = useNavigate();
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);

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

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

    const handleEdit = () => {
      dispatch(
        OPEN_MODAL({
          title: "ویرایش تعاونی",
          content: (
            <EditPoultryCity updateTable={updateTable} item={poultryItem} />
          ),
        })
      );
      handleClose();
    };

    const handleDownload = () => {
      if (poultryItem?.key) {
        window.open(
          `${axios.defaults.baseURL}poultry_monitoring_excel/?key=${poultryItem.key}`,
          "_blank"
        );
      }
      handleClose();
    };

    const handleViewDetails = () => {
      if (poultryItem?.breedingUniqueId) {
        navigate(
          window.location.pathname +
            `${poultryItem.breedingUniqueId}?from=Poultry`
        );
      }
      handleClose();
    };

    return (
      <Grid>
        <Tooltip title={"تنظیمات"} placement="right-start">
          <IconButton
            color="primary"
            className="avicultureActiveRequestsBtn"
            onClick={handleOpen}
          >
            <TuneIcon />
          </IconButton>
        </Tooltip>
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ minWidth: 220, p: 1 }}>
            <ListItemButton
              sx={{ py: 1 }}
              onClick={() => onToggleLimit(!poultryItem?.orderLimit)}
            >
              <ListItemIcon>
                {poultryItem?.orderLimit ? (
                  <ToggleOnIcon color="success" />
                ) : (
                  <ToggleOffIcon color="disabled" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    محدودیت ثبت سفارش
                  </Typography>
                }
              />
            </ListItemButton>
            <ListItemButton onClick={handleViewDetails} sx={{ py: 1 }}>
              <ListItemIcon>
                <VisibilityIcon color="primary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    مشاهده جزییات
                  </Typography>
                }
              />
            </ListItemButton>
            <ListItemButton
              disabled={getRoleFromUrl() === "VetSupervisor"}
              onClick={handleEdit}
              sx={{ py: 1 }}
            >
              <ListItemIcon>
                <ManageAccountsIcon color="secondary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    ویرایش تعاونی
                  </Typography>
                }
              />
            </ListItemButton>
            <ListItemButton onClick={handleDownload} sx={{ py: 1 }}>
              <ListItemIcon>
                <FileDownloadIcon color="success" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    خروجی اکسل
                  </Typography>
                }
              />
            </ListItemButton>
          </List>
        </Popover>
      </Grid>
    );
  };

  const fetchApiData = async (page) => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `total_poultry/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&search=filter&value=${textValue}`
      );
      // Reset error state on successful response
      setHas500Error(false);
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMessage = error?.message || "";
      const status = error?.response?.status;
      const is500Error = errorMessage.includes("500") || status === 500;

      if (is500Error) {
        setHas500Error(true);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      }
      setData([]);
      setTotalRows(0);
    } finally {
      dispatch(LOADING_END());
    }
  };

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

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

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

  useEffect(() => {
    fetchApiData(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    dispatch(provinceGetDashboardPoultriesService({ textValue }))
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
          setDashboardData([]);
        } else if (r?.payload?.data) {
          // Reset error state on successful response
          setHas500Error(false);
          setDashboardData(r.payload.data);
        } else {
          setDashboardData([]);
        }
      })
      .catch((error) => {
        console.error("Error fetching dashboard data:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
        setDashboardData([]);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Reset error state when textValue changes
  useEffect(() => {
    setHas500Error(false);
  }, [textValue]);

  const handleOrderLimitChange = (poultryKey, newChecked) => {
    dispatch(
      getPoultryActiveLimitedService({
        key: poultryKey,
        order_limit: newChecked,
      })
    )
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در تغییر وضعیت محدودیت پیش آمده است!",
              severity: "error",
            });
          }
        } else {
          // Reset error state on successful response
          setHas500Error(false);
          updateTable();
        }
      })
      .catch((error) => {
        console.error("Error updating order limit:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در تغییر وضعیت محدودیت پیش آمده است!",
            severity: "error",
          });
        }
      });
  };

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }

    const d = data.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.unitName || "",
        `${item?.user?.fullname || ""} (${item?.user?.mobile || ""})`,
        item?.breedingUniqueId || "",
        item?.epidemiologicalCode || "",
        item?.healthCertificateNumber || "",
        item?.numberOfHalls || 0,
        item?.totalCapacity ? item.totalCapacity.toLocaleString() : "0",
        `${item?.address?.province?.name || ""}/${
          item?.address?.city?.name || ""
        }`,
        item?.cityOperator || "ندارد",
        item?.vetFarm?.vetFarmName
          ? `${item.vetFarm.vetFarmName} (${item.vetFarm?.vetFarmMobile || ""})`
          : "ندارد",
        `${item?.hatchingInfo?.activeHatching ? "دارد" : "ندارد"} (${
          item?.hatchingInfo?.period || "0"
        })`,
        <Chip
          key={`orderLimitStatus-${i}`}
          label={item?.orderLimit ? "فعال" : "غیرفعال"}
          color={item?.orderLimit ? "success" : "default"}
          variant={item?.orderLimit ? "filled" : "outlined"}
          size="small"
          sx={{
            width: 80,
            justifyContent: "center",
          }}
        />,
        <PoultryActions
          key={`actions-${i}`}
          poultryItem={item}
          onToggleLimit={(checked) =>
            handleOrderLimitChange(item?.key, checked)
          }
        />,
      ];
    });

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

  useEffect(() => {
    // Reset error state when perPage changes
    setHas500Error(false);
    fetchApiData(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [perPage]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    // Reset error state on manual submit (user retry)
    setHas500Error(false);
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `total_poultry/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&search=filter&value=${textValue}`
      );
      // Reset error state on successful response
      setHas500Error(false);
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
      dispatch(LOADING_END());

      dispatch(provinceGetDashboardPoultriesService({ textValue }))
        .then((r) => {
          if (r?.error) {
            const errorMessage = r.error?.message || "";
            const is500Error =
              errorMessage.includes("500") ||
              r.error?.status === 500 ||
              r.error?.statusCode === 500;

            if (is500Error) {
              setHas500Error(true);
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
                severity: "error",
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
                severity: "error",
              });
            }
            setDashboardData([]);
          } else if (r?.payload?.data) {
            setHas500Error(false);
            setDashboardData(r.payload.data);
          } else {
            setDashboardData([]);
          }
        })
        .catch((error) => {
          console.error("Error fetching dashboard data:", error);
          const errorMessage = error?.message || "";
          const status = error?.response?.status;
          const is500Error = errorMessage.includes("500") || status === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
          setDashboardData([]);
        });
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMessage = error?.message || "";
      const status = error?.response?.status;
      const is500Error = errorMessage.includes("500") || status === 500;

      if (is500Error) {
        setHas500Error(true);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      }
      setData([]);
      setTotalRows(0);
      dispatch(LOADING_END());
    }
  };

  return (
    <Grid container xs={10} alignItems="center" justifyContent="center" mt={2}>
      <Grid
        container
        alignItems="center"
        gap={2}
        paddingTop={2}
        paddingRight={2}
        mx={4}
        mb={1}
      >
        <form onSubmit={handleSubmit}>
          <TextField
            id="outlined-basic"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            onClick={handleSubmit}
          >
            جستجو
          </Button>
        </form>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${axios.defaults.baseURL}management_poultry/?key=${
              userKey || ""
            }&role=${getRoleFromUrl()}&search=filter&value=${textValue || ""}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <Grid container mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد مرغداران",
            "تعداد کل دوره جوجه ریزی",
            "حجم کل جوجه ریزی",
            "جوجه ریزی های فعال",
            " حجم جوجه ریزی فعال",
            "حجم مانده در سالن فعال",
            "تعداد کل بار",
            "حجم کل بار",
            "میانگین درصد افت",
          ]}
          data={[
            [
              dashboardData?.poultryCounts
                ? dashboardData.poultryCounts.toLocaleString()
                : "0",
              dashboardData?.allPeriod
                ? dashboardData.allPeriod.toLocaleString()
                : "0",
              dashboardData?.allTotalQuantity
                ? dashboardData.allTotalQuantity.toLocaleString()
                : "0",
              dashboardData?.hatchingPending
                ? dashboardData.hatchingPending.toLocaleString()
                : "0",
              dashboardData?.totalQuantityPoultryHatchingPending
                ? dashboardData.totalQuantityPoultryHatchingPending.toLocaleString()
                : "0",
              dashboardData?.totalLeftOverPoultryHatchingPending
                ? dashboardData.totalLeftOverPoultryHatchingPending.toLocaleString()
                : "0",
              dashboardData?.allKillRequest
                ? dashboardData.allKillRequest.toLocaleString()
                : "0",
              dashboardData?.allKillRequestQuantity
                ? dashboardData.allKillRequestQuantity.toLocaleString()
                : "0",
              dashboardData?.percentLoss
                ? dashboardData.percentLoss.toLocaleString()
                : "0",
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

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