import React, { useContext, useEffect, useState } from "react";
import {
  Autocomplete,
  Button,
  Checkbox,
  IconButton,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getSamasatProvinces } from "../../../../utils/getSamasatProvinces";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  ROUTE_ADMINX_ROUTE_NATIONAL_INFO_SLAUGHTER,
  ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO_SLAUGHTER,
} from "../../../../routes/routes";
import { ProvinceStewardChickenDistributionsAndSalesDashboardService } from "../../services/province-chicken-distribution-and-sales-dashboard";
import { formatTime } from "../../../../utils/formatTime";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const ProvinceChickenStewardSales = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);
  const [dashboardData, setDashboardData] = useState([]);
  const [withDate, setWithDate] = useState(false);

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  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;
    getDashboardData();
    dispatch(LOADING_START());
    response = await axios.get(
      `https://rsibackend.rasadyar.com/app/guilds-transport-carcass-detail/?search=${textValue}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&province=${selectedProvince}&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 getDashboardData = () => {
    dispatch(
      ProvinceStewardChickenDistributionsAndSalesDashboardService({
        province: selectedProvince,
        date1: withDate ? selectedDate1 : null,
        date2: withDate ? selectedDate2 : null,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.info?.role,
        item?.name,
        item?.PartIdCode || item?.jihadiCode,
        item?.Province || item?.province,
        item?.City || item?.city,
        "گوشت مرغ تازه",
        item?.info?.totalInputBuyBarsCount?.toLocaleString(),
        item?.info?.totalInputBuyBarsWight?.toLocaleString(),
        item?.info?.totalOutputBuyBarsCount?.toLocaleString(),
        item?.info?.totalOutputBuyBarsWight?.toLocaleString(),
        item?.info?.totalWareHouse?.toLocaleString(),
        item?.info?.totalInputBuyBarsPercent?.toLocaleString(),
        item?.info?.totalOutputBuyBarsPercent?.toLocaleString(),

        <IconButton
          key={i}
          color="success"
          size="small"
          onClick={() => {
            window.open(
              getRoleFromUrl() === "AdminX"
                ? `${ROUTE_ADMINX_ROUTE_NATIONAL_INFO_SLAUGHTER}/${item?.jihadiCode}/${item?.name}/Steward`
                : `${ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO_SLAUGHTER}/${item?.jihadiCode}/${item?.name}/Steward`,
              "_blank"
            );
          }}
        >
          <VisibilityIcon />
        </IconButton>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `https://rsibackend.rasadyar.com/app/guilds-transport-carcass-detail/?&province=${selectedProvince}&search=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      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 mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد",
            "نقش",
            "محصول",
            "وزن خرید داخل استان",
            "وزن خرید خارج استان",
            "وزن کل خرید",
            "درصد خرید داخل استان",
            "درصد خرید خارج استان",
            "آخرین آپدیت",
          ]}
          data={[
            [
              dashboardData?.totalCountGuild?.toLocaleString(),
              dashboardData?.role,
              dashboardData?.product,
              dashboardData?.totalInputBuyBarsWight?.toLocaleString(),
              dashboardData?.totalOutputBuyBarsWight?.toLocaleString(),
              dashboardData?.totalWareHouse?.toLocaleString(),
              dashboardData?.totalInputBuyBarsPercent?.toLocaleString(),
              dashboardData?.totalOutputBuyBarsPercent?.toLocaleString(),
              dashboardData?.lastUpdate &&
                formatTime(dashboardData?.lastUpdate),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Autocomplete
          sx={{ minWidth: "220px" }}
          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
          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>
        <Tooltip title="خروجی اکسل">
          <Button
            color="success"
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const link = `https://rsibackend.rasadyar.com/app/guilds-transport-carcass-detail-excel/?search=${textValue}${
                withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
              }&province=${selectedProvince}`;
              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>
  );
};
