import React, { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  Button,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
} from "@mui/material";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import axios from "axios";
import { SlaughterHouseSubmitDispenser } from "../slaughter-house-submit-dispenser/SlaughterHouseSubmitDispenser";
import { SlaughterHouseDispensersOperation } from "../slaughter-house-dispensers-operation/SlaughterHouseDispensersOperation";
import { slaughterGetDispenserDashboard } from "../../services/slaughter-house-get-dispenser-dashboard";
import {
  ROUTE_ADMINX_DISPENSER_DETAILS,
  ROUTE_PROVINCE_DISPENSER_DETAILS,
  ROUTE_SLAUGHTER_DISPENSER_DETAILS,
  ROUTE_SUPER_ADMIN_DISPENSER_DETAILS,
} from "../../../../routes/routes";
import { useNavigate } from "react-router-dom";
import { RiSearchLine } from "react-icons/ri";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const SlaughterHouseDispensers = () => {
  const dispatch = useDispatch();

  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 [value, setValue] = useState(0);
  const [dashboardData, setDashboardData] = useState();
  const navigate = useNavigate();

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

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `dispenser/?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(() => {
    fetchApiData(1);
  }, [value]);

  const getDispenserType = (item) => {
    let type = "";
    switch (item?.dispenserType) {
      case "inductor":
        type = "واسطه";
        break;
      case "salesman":
        type = "فروشنده";
        break;
      case "driver":
        type = `راننده - ${item?.car} (${item?.pelak})`;
        break;
      default:
        break;
    }

    return type;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + (perPage * page) / 2 + 1,
        getDispenserType(item),
        item?.user?.fullname,
        item?.user?.mobile,
        item?.user?.city?.cityName,
        item?.killHouse?.name,
        item?.limitationAmount?.toLocaleString(),
        item?.active ? "فعال" : "غیر فعال",
        item?.allocationsInfo?.numberOfAllocations?.toLocaleString(),
        item?.allocationsInfo?.totalWeight?.toLocaleString(),
        item?.allocationsInfo?.totalQuantity?.toLocaleString(),
        item?.allocationsInfo?.numberOfTodayAllocations?.toLocaleString(),
        item?.allocationsInfo?.totalTodayQuantity?.toLocaleString(),
        item?.allocationsInfo?.totalTodayWeight?.toLocaleString(),
        value === 0 ? (
          <SlaughterHouseDispensersOperation
            key={i}
            item={item}
            updateTable={updateTable}
          />
        ) : (
          <Tooltip key={i} title="جزئیات" placement="left">
            <IconButton
              color="success"
              onClick={() => {
                navigate(
                  getRoleFromUrl() === "KillHouse"
                    ? `${ROUTE_SLAUGHTER_DISPENSER_DETAILS}/${item.key}`
                    : getRoleFromUrl() === "AdminX"
                    ? `${ROUTE_ADMINX_DISPENSER_DETAILS}/${item.key}`
                    : getRoleFromUrl() === "SuperAdmin"
                    ? `${ROUTE_SUPER_ADMIN_DISPENSER_DETAILS}/${item.key}`
                    : `${ROUTE_PROVINCE_DISPENSER_DETAILS}/${item.key}`
                );
              }}
            >
              <VisibilityIcon />
            </IconButton>
          </Tooltip>
        ),
      ];
    });

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

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

  useEffect(() => {
    if (value === 1) {
      dispatch(slaughterGetDispenserDashboard()).then((r) => {
        setDashboardData(r.payload.data);
      });
    }
  }, [value]);

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

    try {
      const response = await axios.get(
        `dispenser/?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}>
      <Tabs value={value} onChange={handleChange}>
        <Tab label="توزیع کنندگان" value={0} />
        <Tab label="جزئیات پخش" value={1} />
      </Tabs>
      {value === 0 && (
        <>
          <Grid
            container
            xs={12}
            justifyContent="start"
            alignItems="center"
            gap={2}
          >
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  DRAWER({
                    title: "ثبت توزیع کننده جدید",
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: (
                      <SlaughterHouseSubmitDispenser
                        updateTable={updateTable}
                      />
                    ),
                  })
                );
              }}
            >
              ثبت توزیع کننده
            </Button>
            <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>

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

      {value === 1 && (
        <>
          <Grid
            container
            xs={12}
            justifyContent="start"
            alignItems="center"
            gap={2}
          >
            <Grid container xs={12} justifyContent="start" alignItems="center">
              <ResponsiveTable
                noPagination
                data={[
                  [
                    dashboardData?.numberOfDispensers?.toLocaleString(),
                    dashboardData?.numberOfAllocations?.toLocaleString(),
                    dashboardData?.totalWeight?.toLocaleString(),
                    dashboardData?.totalQuantity?.toLocaleString(),
                    dashboardData?.numberOfTodayAllocations?.toLocaleString(),
                    dashboardData?.totalTodayQuantity?.toLocaleString(),
                    dashboardData?.totalTodayWeight?.toLocaleString(),
                  ],
                ]}
                columns={[
                  "تعداد توزیع کنندگان",
                  "تعداد کل تخصیصات",
                  "وزن تخصیصات کل",
                  "حجم کل",
                  "تخصیصات امروز",
                  "حجم تخصیصات امروز",
                  "وزن امروز",
                ]}
                title={"خلاصه اطلاعات"}
              />
            </Grid>
            <Grid mt={2}>
              <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>

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