import React, { useContext, useEffect, useState } from "react";
import { Button, IconButton, TextField, Tooltip } from "@mui/material";
import { useDispatch } from "react-redux";
import axios from "axios";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import {
  ROUTE_ADMINX_COLD_HOUSES_MANAGEMENT,
  ROUTE_PROVINCE_COLD_HOUSES_MANAGEMENT,
  ROUTE_SUPER_ADMIN_COLD_HOUSES_MANAGEMENT,
} from "../../../../routes/routes";
import { useNavigate } from "react-router-dom";
import { RiFileExcel2Fill } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import { RiSearchLine } from "react-icons/ri";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const ProvinceColdHousesKillHouses = () => {
  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) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `kill-house-cold-house/?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);
  //   };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.name,
        item?.fullname,
        item?.mobile,
        item?.city,
        item?.coldHousesInfo?.totalColdHouses?.toLocaleString(),
        item?.coldHousesInfo?.totalInputWeight?.toLocaleString(),
        item?.coldHousesInfo?.totalAllocatedWeight?.toLocaleString(),
        item?.coldHousesInfo?.totalRemainWeight?.toLocaleString(),
        <Tooltip placement="left" title="نمایش" key={i}>
          <IconButton
            size="small"
            color="success"
            onClick={() => {
              navigate(
                (getRoleFromUrl() === "ProvinceOperator"
                  ? ROUTE_PROVINCE_COLD_HOUSES_MANAGEMENT
                  : getRoleFromUrl() === "AdminX"
                  ? ROUTE_ADMINX_COLD_HOUSES_MANAGEMENT
                  : ROUTE_SUPER_ADMIN_COLD_HOUSES_MANAGEMENT) +
                  "/" +
                  item?.key +
                  "/" +
                  item?.fullname +
                  "/" +
                  "killhouse"
              );
            }}
          >
            <VisibilityIcon />
          </IconButton>
        </Tooltip>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `kill-house-cold-house/?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="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <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>

        <Tooltip title="خروجی اکسل">
          {/* <a
                href={`${axios.defaults.baseURL}0/hatching_excel/`}
                rel="noreferrer"
              > */}
          <Button
            color="success"
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const link = `${axios.defaults.baseURL}management_cold_house_excel`;
              window.location.href = link;
            }}
          >
            <RiFileExcel2Fill size={32} />
          </Button>
          {/* </a> */}
        </Tooltip>
      </Grid>

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