import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import moment from "moment";
import { Button, TextField } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { RiSearchLine } from "react-icons/ri";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import { stawardGetSegmentDashboardService } from "../../../guild/services/steward-get-dashboard-service";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const ProvinceSegmentation = () => {
  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [dashboardData, setDashboardData] = useState([]);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();

  //   const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const getDashboardData = () => {
    dispatch(
      stawardGetSegmentDashboardService({
        value: textValue,
        date1: selectedDate1,
        date2: selectedDate2,
        role: getRoleFromUrl(),
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `kill-house-segmentation-info/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}`
    );

    getDashboardData();
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

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

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.name,
        item?.info?.totalCount?.toLocaleString(),
        item?.info?.totalWeight?.toLocaleString(),
        item?.info?.totalSelfCount?.toLocaleString(),
        item?.info?.totalSelfWeight?.toLocaleString(),
        item?.info?.totalOtherCount?.toLocaleString(),
        item?.info?.totalOtherWeight?.toLocaleString(),
      ];
    });

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

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `kill-house-segmentation-info/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      getDashboardData();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container direction="column" flexWrap="nowrap" mt={SPACING.SMALL}>
      <Grid
        xs={12}
        container
        alignItems="center"
        gap={SPACING.SMALL}
        justifyContent="flex-start"
      >
        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "وزن کل (کیلوگرم)",
              // "تخصیصات مباشر",
              "وزن قطعه بندی",
              // "تخصیصات قطعه بند",
              "وزن تخصیصی به قطعه بندها",
            ]}
            data={[
              [
                dashboardData?.totalWeight?.toLocaleString() || "0",
                // dashboardData?.totalSelfCount?.toLocaleString() || "0",
                dashboardData?.totalSelfWeight?.toLocaleString() || "0",
                // dashboardData?.totalOtherCount?.toLocaleString() || "0",
                dashboardData?.totalOtherWeight?.toLocaleString() || "0",
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>
        <form>
          <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>
              <DatePicker
                label="از تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate1}
                onChange={(e) =>
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"))
                }
              />
            </Grid>
            <Grid>
              <DatePicker
                label="تا تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "160px" }} {...params} />
                )}
                value={selectedDate2}
                onChange={(e) =>
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"))
                }
              />
            </Grid>
            {/* <Tooltip title="خروجی اکسل">
              <Button
                color="success"
                onClick={() => {
                  const link = `${
                    axios.defaults.baseURL
                  }kill_house_free_bar_excel/?role=${getRoleFromUrl()}&key=${userKey}&date1=${selectedDate1}&date2=${selectedDate2}&type=carcass&search=filter&value=${textValue}&date_type=buy`;
                  window.location.href = link;
                }}
              >
                <RiFileExcel2Fill size={32} />
              </Button>
            </Tooltip> */}
          </Grid>
        </form>

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