import React, { useContext, useEffect, useState } from "react";
import { Button, IconButton, TextField } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { ProvinceSubmitBarDifference } from "../province-submit-bar-difference/ProvinceSubmitBarDifference";
import { ProvinceBarDifferencesOperations } from "../province-bar-differences-operations/ProvinceBarDifferencesOperations";
// import EmailIcon from "@mui/icons-material/Email";
import { provinceGetDashboardBarDiffrenceRequest } from "../../services/province-dashboard-bar-diffrence-get-request";
import { ProvinceBarDifferencesModal } from "../province-bar-differences-modal/ProvinceBarDifferencesModal";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceBarDifferenceRequests = ({ state }) => {
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    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 [dashboardData, setDashboardData] = useState([]);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `bar-difference-request/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
          checkPathStartsWith("province")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&page=${page}&page_size=${perPage}&state=${state}&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(
      provinceGetDashboardBarDiffrenceRequest({
        role: getRoleFromUrl(),
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
        state: state,
        filter: "search",
        value: textValue,
        date1: selectedDate1,
        date2: selectedDate2,
      })
    ).then((r) => {
      if (r.payload?.data) {
        setDashboardData(r.payload.data);
      }
    });
  };

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

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

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
    fetchDashboardData();
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.registerFullname,
        formatJustDate(item?.createDate),
        `${item?.hatching?.poultry?.unitName || ""} (${
          item?.hatching?.poultry?.user?.mobile || ""
        })`,
        `${item?.killHouse?.name || ""} (${
          item?.killHouse?.killHouseOperator?.user?.mobile || ""
        })`,
        item?.barInfo?.totalQuantity?.toLocaleString(),
        item?.barInfo?.totalWeight?.toLocaleString(),
        item?.barInfo?.firstTotalQuantity?.toLocaleString(),
        item?.barInfo?.differenceQuantity?.toLocaleString(),
        item?.quantity?.toLocaleString(),
        item?.weight?.toLocaleString(),

        item?.acceptorImages?.[0] ||
        item?.acceptorMessage ||
        item?.registerMessage ||
        item?.violationImage?.[0] ? (
          <Grid container key={i}>
            <IconButton
              variant="contained"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    content: <ProvinceBarDifferencesModal item={item} />,
                    title: "پیوست",
                  })
                );
              }}
            >
              ✉️
            </IconButton>
          </Grid>
        ) : (
          "-"
        ),

        item.state === "pending"
          ? "در انتظار تایید"
          : item.state === "rejected"
          ? "رد شده"
          : "تایید شده",
        state === "pending" ? (
          <ProvinceBarDifferencesOperations
            key={i}
            updateTable={updateTable}
            item={item}
          />
        ) : (
          "-"
        ),
      ];
    });

    setTableData(d);
  }, [data, state, page, perPage]);

  useEffect(() => {
    fetchApiData(1);
    fetchDashboardData();
  }, [state, perPage, selectedDate1, selectedDate2, selectedSubUser?.key]);

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchApiData(1);
    fetchDashboardData();
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "تعداد",
              "وزن تقریبی کشتار",
              "حجم سفارشات دریافتی توسط کشتارگاه",
              "اختلاف کشتار (حجم)",
              "اختلاف حجم",
              "اختلاف وزن",
            ]}
            data={[
              [
                dashboardData?.count?.toLocaleString(),
                dashboardData?.totalWeight?.toLocaleString(),
                dashboardData?.firstTotalQuantity?.toLocaleString(),
                dashboardData?.differenceQuantity?.toLocaleString(),
                dashboardData?.quantity?.toLocaleString(),
                dashboardData?.weight?.toLocaleString(),
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>
        {getRoleFromUrl() !== "KillHouse" && (
          <Grid>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: (
                      <ProvinceSubmitBarDifference updateTable={updateTable} />
                    ),
                    title: " ثبت اختلاف کشتار",
                  })
                );
              }}
            >
              ثبت اختلاف کشتار
            </Button>
          </Grid>
        )}
        <Grid>
          <DatePicker
            label="از تاریخ"
            renderInput={(params) => (
              <TextField {...params} style={{ width: "160px" }} size="small" />
            )}
            value={selectedDate1}
            onChange={(newValue) => {
              setSelectedDate1(moment(newValue).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            renderInput={(params) => (
              <TextField {...params} style={{ width: "160px" }} size="small" />
            )}
            value={selectedDate2}
            onChange={(newValue) => {
              setSelectedDate2(moment(newValue).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button type="submit" endIcon={<RiSearchLine />}>
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        customColors={[
          {
            name: "اختلاف حجم",
            color: "#ff5555",
          },
          {
            name: "اختلاف وزن",
            color: "#ff5555",
          },
        ]}
        columns={[
          "ردیف",
          "ثبت کننده",
          "تاریخ ثبت",
          "مرغدار",
          "کشتارگاه",
          "حجم کم شده از سالن مرغدار",
          "وزن تقریبی کشتار (کیلوگرم)",
          "حجم سفارشات دریافتی توسط کشتارگاه",
          " اختلاف کشتار(حجم)",
          "اختلاف حجم",
          "اختلاف وزن",
          "پیوست",
          "وضعیت",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={state === "pending" ? "اختلاف کشتار" : "بایگانی اختلاف کشتار"}
      />
    </Grid>
  );
};
