import { Button, Tab, Tabs, TextField } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { ReturnedAllocated } from "./ProvinceReturnedAllocated";
import { ReturnedCargo } from "./ProvinceReturnedCargo";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { RiSearchLine } from "react-icons/ri";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch, useSelector } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceReturnPurchases = () => {
  const dispatch = useDispatch();
  const [selectedTab, setSelectedTab] = useState(0);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);
  const [dashboardData, setDashboardData] = useState({});
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const [textValue, setTextValue] = useState("");
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const fetchDashboard = async () => {
    try {
      const response = await axios.get(
        `return-requests-dashboard/?role=${getRoleFromUrl()}${
          checkPathStartsWith("province")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&date1=${selectedDate1}&date2=${selectedDate2}`
      );
      setDashboardData(response.data);
    } catch (error) {
      console.error("Error fetching dashboard data:", error);
    }
  };

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

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
    setPage(1);
  };

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const endpoint =
        selectedTab === 0
          ? "return-province-kill-requests"
          : "return-kill-house-requests";

      const response = await axios.get(
        `${endpoint}/?role=${getRoleFromUrl()}${
          checkPathStartsWith("province")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${textValue}&page_size=${perPage}&page=${page}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
      dispatch(LOADING_END());
    }
  };

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

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

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

  const handleSubmit = () => {
    fetchApiData(page);
    fetchDashboard();
  };

  const updateTable = () => {
    fetchApiData(page);
    fetchDashboard();
  };

  return (
    <Grid>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        gap={SPACING.SMALL}
      >
        <Grid style={{ width: 160 }}>
          <DatePicker
            label="از تاریخ"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid style={{ width: 160 }}>
          <DatePicker
            label="تا تاریخ"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>

        <Grid container alignItems="center" gap={SPACING.SMALL}>
          <TextField
            size="small"
            autoComplete="off"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            type="submit"
            onClick={handleSubmit}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </Grid>
      </Grid>
      <Grid mb={SPACING.MEDIUM} mt={SPACING.MEDIUM}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد کل تخصیصات",
            "تعداد تخصیصات بازگشتی کاربر",
            "تعداد تخصیصات بازگشتی سیستم",
            "حجم کل تخصیصات",
            "حجم تخصیصات بازگشتی کاربر",
            "حجم تخصیصات بازگشتی سیستم",
            "وزن کل تخصیصات",
            "وزن بازگشتی کاربر",
            "وزن بازگشتی سیستم",
            "تعداد کل بارها",
            "تعداد بارهای عدم وصول",
            "تعداد بارهای بازگشتی سیستمی ",
            "حجم کل بارها",
            "حجم بارهای عدم وصول",
            "حجم بارهای بازگشتی سیستمی ",
            "وزن کل بارها",
            "وزن بارهای عدم وصول",
            "وزن بارهای بازگشتی سیستمی ",
            "وزن خریدهای بازگشتی با کارمزد",
            "کارمزد خریدهای بازگشتی",
          ]}
          data={[
            [
              dashboardData?.provinceKillRequestTotalCount?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalOperatorReturnCount?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalSystemReturnCount?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalQuantity?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalOperatorReturnQuantity?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalSystemReturnQuantity?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalWeight?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalOperatorReturnWeight?.toLocaleString() ||
                "0",
              dashboardData?.provinceKillRequestTotalSystemReturnWeight?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalCount?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalNonReceiptCount?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalSystemReturnCount?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalQuantity?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalNonReceiptQuantity?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalSystemReturnQuantity?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalWeight?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalNonReceiptWeight?.toLocaleString() ||
                "0",
              dashboardData?.killHouseRequestTotalSystemReturnWeight?.toLocaleString() ||
                "0",
              dashboardData?.totalReturnWeightWithWage?.toLocaleString() || "0",
              dashboardData?.totalReturnWage?.toLocaleString() || "0",
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        mb={SPACING.SMALL}
        mt={SPACING.LARGE}
      >
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={selectedTab}
          onChange={handleTabChange}
        >
          <Tab label="تخصیص‌های بازگشتی" />
          <Tab label="بارهای بازگشتی" />
        </Tabs>
      </Grid>
      {selectedTab === 0 && (
        <ReturnedAllocated
          data={data}
          page={page}
          perPage={perPage}
          totalRows={totalRows}
          handlePageChange={handlePageChange}
          handlePerRowsChange={handlePerRowsChange}
          textValue={textValue}
          updateTable={updateTable}
        />
      )}
      {selectedTab === 1 && (
        <ReturnedCargo
          data={data}
          page={page}
          perPage={perPage}
          totalRows={totalRows}
          handlePageChange={handlePageChange}
          handlePerRowsChange={handlePerRowsChange}
          textValue={textValue}
          updateTable={updateTable}
        />
      )}
    </Grid>
  );
};
