import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { reportsList } from "./reportList";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { Button, IconButton, TextField, Typography } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import { adminXGetReportStatusService } from "../../services/admin-x-get-report-status-service";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ManageSearchIcon from "@mui/icons-material/ManageSearch";

export const AdminCExcelStatus = () => {
  const [tableData, setTableData] = useState([]);
  const userKey = useSelector((state) => state.userSlice?.userProfile?.key);
  const authToken = useSelector((state) => state.userSlice?.authToken);
  const [loadingIndex, setLoadingIndex] = useState(null);
  const [allReports, setAllReports] = useState([]);
  const [update, setUpdate] = useState(false);

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const dispatch = useDispatch();

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

  useEffect(() => {
    const newData = reportsList.map((report) => ({
      ...report,
      status: "",
    }));
    setAllReports(newData);
  }, []);

  function replaceUrlParams(url, date1, date2, role, key, token) {
    if (!url || typeof url !== "string") {
      return url || "";
    }

    const [baseUrl, queryString] = url.split("?");

    if (!queryString) {
      return url;
    }

    const params = new URLSearchParams(queryString);

    if (params.has("date1")) {
      params.set("date1", date1);
    }
    if (params.has("date2")) {
      params.set("date2", date2);
    }

    if (params.has("start")) {
      params.set("start", date1);
    }
    if (params.has("end")) {
      params.set("end", date2);
    }

    if (params.has("role")) {
      params.set("role", role);
    }

    if (params.has("token")) {
      params.set("token", token);
    }

    if (params.has("key")) {
      params.set("key", key);
    }

    return `${baseUrl}?${params.toString()}`;
  }

  const handleCheckAll = async () => {
    const updatedData = [...allReports];
    for (let i = 0; i < allReports.length; i++) {
      setLoadingIndex(i);
      try {
        const response = await dispatch(
          adminXGetReportStatusService({
            url: replaceUrlParams(
              allReports[i]?.url,
              selectedDate1,
              selectedDate2,
              getRoleFromUrl(),
              userKey,
              authToken
            ),
          })
        );

        if (response?.payload?.data?.status) {
          updatedData[i].status = response.payload.data.status;
        }
      } catch (error) {
        console.error("Error fetching report status:", error);
      }
    }
    setLoadingIndex(null);
    setAllReports(updatedData);
    setUpdate((prevUpdate) => !prevUpdate);
  };

  const handleSingleCheck = async (index) => {
    setLoadingIndex(index);
    try {
      const response = await dispatch(
        adminXGetReportStatusService({
          url: replaceUrlParams(
            allReports[index]?.url,
            selectedDate1,
            selectedDate2,
            getRoleFromUrl(),
            userKey,
            authToken
          ),
        })
      );

      const newData = [...allReports];
      if (response?.payload?.data?.status) {
        newData[index].status = response.payload.data.status;
      }
      setAllReports(newData);
    } catch (error) {
      console.error("Error fetching report status:", error);
    } finally {
      setLoadingIndex(null);
    }
  };

  useEffect(() => {
    const d = allReports.map((item, i) => [
      i + 1,
      item?.title || "",
      item?.url ? item.url.split("/")[0] : "",
      <IconButton
        color="primary"
        key={`button-${i}`}
        onClick={() => handleSingleCheck(i)}
        disabled={loadingIndex === i}
      >
        <ManageSearchIcon />
      </IconButton>,
      item?.status ? (
        <Typography
          key={`status-${i}`}
          style={{
            color:
              parseInt(item.status) === 200 || item.status === "200"
                ? "green"
                : "red",
            fontWeight: "bold",
          }}
        >
          ({item.status}){" "}
          {parseInt(item.status) === 200 || item.status === "200"
            ? "سالم"
            : "مشکل دارد"}
        </Typography>
      ) : (
        "-"
      ),
    ]);

    setTableData(d);
  }, [allReports, loadingIndex, update]);

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center">
      <Grid container gap={SPACING.SMALL} alignItems="center">
        <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>
        <Grid>
          <Button variant="contained" onClick={handleCheckAll}>
            تست همگانی
          </Button>
        </Grid>
      </Grid>
      <ResponsiveTable
        title="بررسی اکسل"
        noPagination
        data={tableData}
        columns={["ردیف", "عنوان", "آدرس", "بررسی", "وضعیت"]}
      />
    </Grid>
  );
};
