import { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { Button, Checkbox, Tab, Tabs, TextField, Tooltip } from "@mui/material";
import axios from "axios";
import { RiFileExcel2Fill } from "react-icons/ri";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { DatePicker } from "@mui/x-date-pickers";
import { ProvinceDispenserSaleOut } from "../province-dispenser-sale-out/ProvinceDispenserSaleOut";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import { SPACING } from "../../../../data/spacing";
import { ProvinceSaleInDispenser } from "../province-sale-dispenser/ProvinceSaleInDispenser";
import { provinceGetDispenserSlaughterToStewardDashboardService } from "../../services/province-dispenser-slaughter-get-steward-service";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ProvinceDispenserSegmentation } from "../province-dispenser-segmentation/ProvinceDispenserSegmentation";

export const ProvinceDispencerSaleDistribution = () => {
  const [data, setData] = useState([]);
  const [withDate, setWithDate] = useState(false);
  const [dashboardData, setDashboardData] = useState([]);
  const [openNotif] = useContext(AppContext);
  const [value, setValue] = useState(0);
  const [page, setPage] = useState(1);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [tableData, setTableData] = useState([]);

  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const dispatch = useDispatch();

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `/total-steward-dashboard-detail/?&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

  const fetchDashboardData = () => {
    dispatch(
      provinceGetDispenserSlaughterToStewardDashboardService({
        selectedDate1: withDate ? selectedDate1 : null,
        selectedDate2: withDate ? selectedDate2 : null,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchTableData = () => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.user?.fullname?.toLocaleString()} ${item?.user?.mobile?.toLocaleString()}`,
        `${item?.steward ? "مباشر" : "صنف"} `,
        item?.address?.city?.name || item?.user?.cityName,
        item?.wareHouseInfo?.totalBarsWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalEnteredBarsWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalOutputWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalRemainWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalRemainGovernmentalWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalRemainFreeWeight?.toLocaleString(),
        item?.wareHouseInfo?.inputBarsWeight?.toLocaleString(),
        item?.wareHouseInfo?.freeBarsWeight?.toLocaleString(),
        item?.wareHouseInfo?.inProvinceBarsWeight?.toLocaleString(),
        item?.wareHouseInfo?.outProvinceBarsWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalOutputGovernmentalWeight?.toLocaleString(),
        item?.wareHouseInfo?.totalOutputFreeWeight?.toLocaleString(),
        item?.wareHouseInfo?.lastTotalRemainWeight?.toLocaleString(),
        item?.wareHouseInfo?.lastTotalRemainGovernmentalWeight?.toLocaleString(),
        item?.wareHouseInfo?.lastTotalRemainFreeWeight?.toLocaleString(),
        item?.wareHouseInfo?.segmentationsWeight?.toLocaleString(),
      ];
    });
    setTableData(d);
  };

  useEffect(() => {
    if (value === 0) {
      fetchApiData(page);
      fetchDashboardData();
    }
  }, [value]);

  useEffect(() => {
    if (value === 0) {
      fetchApiData(page);
      fetchDashboardData();
    }
  }, [dispatch, selectedDate1, selectedDate2, perPage, withDate]);

  useEffect(() => {
    if (value === 0) {
      fetchTableData();
    }
  }, [data, perPage]);

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

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

  return (
    <Grid container xs={12} justifyContent="start" alignItems="center">
      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        mt={2}
      >
        <Grid
          container
          justifyContent="center"
          alignItems="center"
          mb={SPACING.MEDIUM}
          xs={12}
        >
          <Tabs
            scrollButtons="auto"
            variant="scrollable"
            allowScrollButtonsMobile
            onChange={handleChange}
            value={value}
          >
            <Tab label="اطلاعات جامع" />
            <Tab label="توزیع  به داخل استان" />
            <Tab label="فروش به خارج استان" />
            <Tab label="قطعه بندی" />
          </Tabs>
        </Grid>
      </Grid>

      {value === 0 && (
        <>
          <ResponsiveTable
            changed
            title="اطلاعات کلی انبار"
            noPagination
            columns={[
              "وزن کل بار ها (کیلوگرم)",
              "وزن وارد شده به انبار (کیلوگرم)",
              "وزن دولتی (کیلوگرم)",
              "وزن آزاد (کیلوگرم)",
              "وزن توزیع شده داخل استان (کیلوگرم)",
              "وزن توزیع شده خارج استان (کیلوگرم)",
              "وزن قطعه بندی",
              "کل وزن فروش رفته دولتی",
              "کل وزن فروش رفته آزاد",
              "مانده انبار (کیلوگرم)",
              "مانده انبار دولتی (کیلوگرم)",
              "مانده انبار آزاد (کیلوگرم)",
            ]}
            data={[
              [
                dashboardData?.totalBarsWeight?.toLocaleString(),
                dashboardData?.totalEnteredBarsWeight?.toLocaleString(),
                dashboardData?.totalGovernmentalInputWeight?.toLocaleString(),
                dashboardData?.totalFreeInputWeight?.toLocaleString(),
                dashboardData?.inProvinceBarsWeight?.toLocaleString(),
                dashboardData?.outProvinceBarsWeight?.toLocaleString(),
                dashboardData?.segmentationsWeight?.toLocaleString(),
                dashboardData?.totalGovernmentalOutputWeight?.toLocaleString(),
                dashboardData?.totalFreeOutputWeight?.toLocaleString(),
                dashboardData?.totalRemainWeight?.toLocaleString(),
                dashboardData?.totalGovernmentalRemainWeight?.toLocaleString(),
                dashboardData?.totalFreeRemainWeight?.toLocaleString(),
              ],
            ]}
          />
          <Grid
            mt={2}
            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>

          <Tooltip title="خروجی اکسل">
            <Button
              color="success"
              onClick={() => {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                  severity: "success",
                });
                const link = `${
                  axios.defaults.baseURL
                }total_steward_dashboard_excel/?key=${userKey}${
                  withDate
                    ? `&date1=${selectedDate1}&date2=${selectedDate2}`
                    : ``
                }`;
                window.location.href = link;
              }}
            >
              <RiFileExcel2Fill size={32} />
            </Button>
          </Tooltip>

          <Grid
            container
            xs={12}
            justifyContent="center"
            alignItems="center"
            mt={2}
          >
            <ResponsiveTable
              title="انبار و توزیع"
              columns={[
                "ردیف",
                "خریدار",
                "ماهیت",
                "شهر",
                "وزن کل بارها",
                "کل وزن ورودی به انبار",
                "کل وزن فروش رفته",
                "مانده انبار فعلی",
                "مانده انبار دولتی (کیلوگرم)",
                "مانده انبار آزاد (کیلوگرم)",
                "وزن بار درون استان",
                "وزن لاشه خرید خارج استان",
                "وزن فروش داخل استان",
                "وزن فروش خارج استان",
                "کل وزن فروش رفته دولتی",
                "کل وزن فروش رفته آزاد",
                "مانده انبار گذشته",
                "مانده انبار گذشته دولتی",
                "مانده انبار گذشته آزاد",
                "وزن فطعه بندی",
              ]}
              handlePageChange={handlePageChange}
              data={tableData}
              totalRows={totalRows}
              page={page}
              perPage={perPage}
              handlePerRowsChange={handlePerRowsChange}
            />
          </Grid>
        </>
      )}

      {value === 1 && <ProvinceSaleInDispenser />}

      {value === 2 && <ProvinceDispenserSaleOut />}

      {value === 3 && <ProvinceDispenserSegmentation />}
    </Grid>
  );
};
