import { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import moment from "moment";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  Checkbox,
  IconButton,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { DatePicker } from "@mui/x-date-pickers";
import { useParams } from "react-router-dom";
import { getSamasatProvinces } from "../../../../utils/getSamasatProvinces";
import { provinceNationalInfoSlaughterhouseGetDashboardService } from "../../../city/services/province-national-info-slughter-house-service";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";
import TuneIcon from "@mui/icons-material/Tune";
import DownloadIcon from "@mui/icons-material/Download";
import {
  ROUTE_ADMINX_ROUTE_NATIONAL_INFO_SLAUGHTER,
  ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO_SLAUGHTER,
  ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO_SLAUGHTER,
} from "../../../../routes/routes";
import { RiFileExcel2Fill } from "react-icons/ri";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";

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

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

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

  const open = Boolean(anchorEl);
  const id = open ? "slaughter-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: "details",
      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 ProvinceNationalInfoSlaughterhouse = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [withDate, setWithDate] = useState(false);

  const [data, setData] = useState([]);
  const [dashboardData, setDashboardData] = 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 { key } = useParams();

  const getDashboardData = () => {
    dispatch(
      provinceNationalInfoSlaughterhouseGetDashboardService({
        date1: withDate ? selectedDate1 : null,
        date2: withDate ? selectedDate2 : null,
        search: textValue,
        province: key || selectedProvince ? selectedProvince : "",
        role: getRoleFromUrl(),
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `https://rsibackend.rasadyar.com/app/total-killhouse/?search=${textValue}&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}&province=${
        key || selectedProvince ? selectedProvince : ""
      }`
    );

    getDashboardData();
    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);
  //   };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.UnitName,
        item?.PartIdCode,
        item?.Province,
        item?.City,
        item?.info?.bars?.toLocaleString(),
        item?.info?.totalBarsQuantity?.toLocaleString(),
        item?.info?.inputBars?.toLocaleString(),
        item?.info?.totalInputBarsQuantity?.toLocaleString(),
        item?.info?.totalInputBarsPercent[0]
          ? item?.info?.totalInputBarsPercent[0]?.toFixed(1)
          : item?.info?.totalInputBarsPercent,
        item?.info?.outputBars?.toLocaleString(),
        item?.info?.totalOutputBarsQuantity?.toLocaleString(),
        item?.info?.totalOutputBarsPercent?.toFixed(1),
        <SlaughterActionsMenu
          key={item?.PartIdCode || i}
          excelHref={`https://rsibackend.rasadyar.com/app/transporting_detail_excel/?PartIdCode=${
            item.PartIdCode
          }&province=${key || selectedProvince ? selectedProvince : ""}${
            withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
          }`}
          onView={() =>
            window.open(
              getRoleFromUrl() === "AdminX"
                ? `${ROUTE_ADMINX_ROUTE_NATIONAL_INFO_SLAUGHTER}/${item.PartIdCode}/${item?.UnitName}`
                : getRoleFromUrl() === "SuperAdmin"
                ? `${ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO_SLAUGHTER}/${item.PartIdCode}/${item?.UnitName}`
                : `${ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO_SLAUGHTER}/${item.PartIdCode}/${item?.UnitName}`,
              "_blank"
            )
          }
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `https://rsibackend.rasadyar.com/app/total-killhouse/?role=${getRoleFromUrl()}&search=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&province=${
          key || selectedProvince ? selectedProvince : ""
        }`
      );

      setData(response.data.results);
      setTotalRows(response.data.count);
      getDashboardData();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

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

  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
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
        >
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  sx={{ width: { xs: "126px", md: "160px" } }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  sx={{ width: { xs: "126px", md: "160px" } }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </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>
          <Tooltip placement="right" title="دانلود اکسل">
            <IconButton
              size="small"
              color="success"
              component="a"
              href={`https://rsibackend.rasadyar.com/app/total_killhouse_excel/?search=${textValue}${
                withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
              }&province=${key || selectedProvince ? selectedProvince : ""}`}
            >
              <RiFileExcel2Fill size={36} />
            </IconButton>
          </Tooltip>
        </Grid>
      </Grid>
      <Grid container mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد کشتارگاه ها",
            "تعداد بارها",
            "حجم بارها",
            "حجم بار های داخل استان",
            "حجم بار های خارج استان",
            "بیشترین حجم خرید",
            "حجم خرید",
            "کمترین حجم خرید",
            "میزان کمترین حجم",
          ]}
          data={[
            [
              dashboardData?.killHouseCount?.toLocaleString(),
              dashboardData?.bars?.toLocaleString(),
              dashboardData?.totalBarsQuantity?.toLocaleString(),
              dashboardData?.totalInputBarsQuantity?.toLocaleString(),
              dashboardData?.totalOutputBarsQuantity?.toLocaleString(),
              dashboardData?.topKillHouseName?.toLocaleString(),
              dashboardData?.topKillHouseAmount?.toLocaleString(),
              dashboardData?.lowKillHouseName?.toLocaleString(),
              dashboardData?.lowKillHouseAmount?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

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