import React, { useEffect, useState } from "react";
import {
  Autocomplete,
  Button,
  IconButton,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";

import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { useNavigate, useParams } from "react-router-dom";
import {
  ROUTE_ADMINX_ROUTE_NATIONAL_INFO_FARM,
  ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO_FARM,
  ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO_FARM,
} from "../../../../routes/routes";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";
import TuneIcon from "@mui/icons-material/Tune";
import DownloadIcon from "@mui/icons-material/Download";
import { provinceNationalFarmManagementInfoDashboardService } from "../../services/province-national-info-farm-management-info-dashboard-service";
import { getSamasatProvinces } from "../../../../utils/getSamasatProvinces";

const FarmActionsMenu = ({ excelHref, onView }) => {
  const [anchorEl, setAnchorEl] = useState(null);

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

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

  const open = Boolean(anchorEl);
  const id = open ? "farm-actions-menu" : undefined;

  const options = [
    {
      key: "excel",
      label: "دانلود اکسل",
      color: "success.main",
      icon: <DownloadIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: () => {
        window.open(excelHref, "_blank", "noopener");
      },
    },
    {
      key: "view",
      label: "نمایش جزئیات",
      color: "primary.main",
      icon: <RemoveRedEyeIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: onView,
    },
  ];

  return (
    <Grid container alignItems="center" justifyContent="center" gap={0.5}>
      <Tooltip title="عملیات">
        <IconButton
          aria-describedby={id}
          color="primary"
          onClick={handleOpen}
          size="small"
        >
          <TuneIcon fontSize="small" />
        </IconButton>
      </Tooltip>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        slotProps={{
          paper: {
            sx: {
              mt: 1,
            },
          },
        }}
      >
        <List sx={{ p: 1 }}>
          {options.map((option) => (
            <ListItemButton
              key={option.key}
              onClick={() => {
                handleClose();
                option.action();
              }}
              sx={{
                borderRadius: 1,
                mb: 0.5,
                color: option.color,
                "&:last-of-type": {
                  mb: 0,
                },
              }}
            >
              <ListItemIcon sx={{ color: option.color, minWidth: 36 }}>
                {option.icon}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography
                    sx={{
                      color: option.color,
                      fontWeight: 600,
                      fontSize: { xs: "13px", md: "14px" },
                    }}
                  >
                    {option.label}
                  </Typography>
                }
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </Grid>
  );
};

export const ProvinceNationalInfoFarms = () => {
  const navigate = useNavigate();
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const [selectedProvince, setSelectedProvince] = useState("");

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [dashboardData, setDashboardData] = useState([]);
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const dispatch = useDispatch();
  const { key } = useParams();

  const getDashboardData = () => {
    dispatch(
      provinceNationalFarmManagementInfoDashboardService({
        search: textValue,
        province: selectedProvince === "همه" ? "" : selectedProvince,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `https://rsibackend.rasadyar.com/app/poultry-info/?search=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&province=${
        key || selectedProvince ? selectedProvince : ""
      }`
    );
    dispatch(LOADING_END());
    getDashboardData();
    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);
  //   };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const name = (item.FirstName + "" + item.LastName).replace("null", "");
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        name,
        item?.Mobile,
        item?.UnitName,
        item?.EpidemiologicCode,
        item?.SystemCode,
        item?.UnitId,
        item?.UserIsActiveDescription,
        item?.info?.capacity?.toLocaleString(),
        item?.Province,
        item?.City,
        item?.info?.countHatching?.toLocaleString(),
        item?.info?.totalHatching?.toLocaleString(),
        item?.info?.totalEvacuation?.toLocaleString(),
        item?.info?.totalEvacuationPercent?.toLocaleString(),
        item?.info?.totalKilling?.toLocaleString(),
        item?.info?.totalKillingPercent?.toLocaleString(),
        item?.info?.totalLeftover?.toLocaleString(),
        item?.info?.totalLeftOverPercent?.toLocaleString(),
        item?.info?.carsCount?.toLocaleString(),
        item?.info?.totalCars?.toLocaleString(),
        <FarmActionsMenu
          key={item?.SystemCode || i}
          excelHref={`https://rsibackend.rasadyar.com/app/hatching_excel/?system_code=${
            item.SystemCode
          }&province=${key || selectedProvince ? selectedProvince : ""}`}
          onView={() => {
            navigate(
              getRoleFromUrl() === "AdminX"
                ? `${ROUTE_ADMINX_ROUTE_NATIONAL_INFO_FARM}/${item?.SystemCode}/${name}`
                : getRoleFromUrl() === "SuperAdmin"
                ? `${ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO_FARM}/${item?.SystemCode}/${name}`
                : `${ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO_FARM}/${item?.SystemCode}/${name}`
            );
          }}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `https://rsibackend.rasadyar.com/app/poultry-info/?role=${getRoleFromUrl()}&search=${textValue}&page=${1}&page_size=${perPage}&province=${
          key || selectedProvince ? selectedProvince : ""
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
      getDashboardData();
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const getProvinceList = () => {
    return [{ name: "همه" }, ...getSamasatProvinces()];
  };

  const getProvince = (item) => {
    if (!key && (selectedProvince === "همه" || !selectedProvince)) {
      return [item ? item?.provinceCount?.toLocaleString() : "تعداد استان"];
    } else {
      return [];
    }
  };
  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        {!key && (
          <Grid minWidth={210}>
            <Autocomplete
              size="small"
              disablePortal
              id="hatching"
              options={getProvinceList().map((i) => {
                return {
                  label: i.name,
                };
              })}
              onChange={(event, value) => {
                if (value.label !== "همه") {
                  setSelectedProvince(value.label);
                } else {
                  setSelectedProvince("");
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label="انتخاب استان" />
              )}
            />
          </Grid>
        )}

        <Grid>
          <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>
        </Grid>
      </Grid>

      <Grid container mt={2} mb={4} isDashboard gap={2}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            " تعداد  فارم ها ",
            "تعداد کل جوجه ریزی",
            "حجم کل جوجه ریزی",
            "تلفات",
            "درصد تلفات",
            "کشتار شده",
            "درصد کشتار شده",
            "مانده درسالن",
            "درصد مانده درسالن",

            "میانگین سن کشتار",
            ...getProvince(),
            "تعداد شهرستان",
          ]}
          data={[
            [
              dashboardData?.poultryCount?.toLocaleString(),
              dashboardData?.totalHatchingCount?.toLocaleString(),
              dashboardData?.totalHatchingQuantity?.toLocaleString(),
              dashboardData?.totalHatchingEvacuation?.toLocaleString(),
              dashboardData?.totalHatchingEvacuationPercent?.toLocaleString(),
              dashboardData?.totalHatchingKillingQuantity?.toLocaleString(),
              dashboardData?.totalHatchingKillingQuantityPercent?.toLocaleString(),
              dashboardData?.totalHatchingLeftOver?.toLocaleString(),
              dashboardData?.totalHatchingLeftOverPercent?.toLocaleString(),

              Math.floor(
                dashboardData?.totalHatchingKillingAge?.toLocaleString()
              ),
              dashboardData?.provinceCount?.toLocaleString(),
              dashboardData?.cityCount?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات فارم ها"}
        />
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد  جوجه ریزی های فعال",
            "حجم  جوجه ریزی ها",
            "تلفات",
            "درصد تلفات",
            "کشتار شده",
            "درصد کشتار شده",
            "مانده در سالن",
            "درصد مانده در سالن",
            "میانگین سن کشتار",
            "مانده در سالن آماده به کشتار",
            "درصد مانده در سالن آماده به کشتار",
          ]}
          data={[
            [
              dashboardData?.totalActiveHatchingCount?.toLocaleString(),
              dashboardData?.totalActiveHatchingQuantity?.toLocaleString(),
              dashboardData?.totalActiveHatchingEvacuation?.toLocaleString(),
              dashboardData?.totalActiveHatchingEvacuationPercent?.toLocaleString(),
              dashboardData?.totalActiveHatchingKillingQuantity?.toLocaleString(),
              dashboardData?.totalActiveHatchingKillingQuantityPercent?.toLocaleString(),
              dashboardData?.totalActiveHatchingLeftOver?.toLocaleString(),
              dashboardData?.totalActiveHatchingLeftOverPercent?.toLocaleString(),

              Math.floor(
                dashboardData?.totalActiveHatchingKillingAge
              )?.toLocaleString(),
              dashboardData?.totalReadyActiveHatchingLeftOver?.toLocaleString(),

              dashboardData?.totalReadyHatchingLeftOverPercent?.toLocaleString(),
            ],
          ]}
          title={"  جوجه ریزی های فعال (1 تا 70 روز)"}
          allColors={{ color: "#6262c4", text: "white" }}
        />
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "نام و نام خانوادگی",
          "شماره همراه",
          "نام واحد",
          "کد اپیدمیولوژیک",
          "کد سیستمی واحد",
          "شناسه یکتا واحد",
          "وضعیت",
          "ظرفیت فارم",
          "استان",
          "شهرستان",
          "تعداد جوجه ریزی",
          "حجم جوجه ریزی",
          "تلفات",
          "درصد تلفات",
          "کشتار شده",
          "درصد کشتار",
          "مانده در سالن",
          "درصد مانده در سالن ",
          "تعداد ماشین",
          "حجم ماشین ها",
          "جزئیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={`مدیریت فارم ${key || ""}`}
      />
    </Grid>
  );
};
