import React, { useState, useEffect, useRef } from "react";
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Breadcrumb, Layout, Menu, Typography, theme } from "antd";
import { ToastContainer, toast } from "react-toastify";
import { Box, Button } from "@mui/material";
import TextField from "@mui/material/TextField";
import EditButton from "./EditButton";
import { width } from "@mui/system";
import "react-toastify/dist/ReactToastify.css";
import { useSearchParams } from "react-router-dom";
import LoadingContainer from "./LoadingContainer";
import HomeIcon from "@mui/icons-material/Home";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { useNavigate } from "react-router-dom";
import QueryStatsIcon from "@mui/icons-material/QueryStats";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";
import {
  updatePartAanomolyData,
  updatePlaygroundCurrentPage,
  updatePlaygroundResults,
  updatePlaygroundTotalPages,
  updateSystemNo,
} from "../redux/actions/actions";
import { Select } from "antd";

import CustomQueryExecutorCard from "./CustomQueryExecutorCard";
import SimpleDialog from "./SimpleDialog";
import SystemNumberDialog from "./SystemNumberDialog";
import ValidationContainer from "./ValidationContainer";
import QueryExecutorCard from "./QueryExecutorCard";
import ArrowUpwardIcon from "@mui/icons-material/ArrowUpward";
import QueryExecutortextArea from "./QueryExecutortextArea";
import AntdesignLayout from "./AntdesignLayout";
import TextInputField from "./TextInputField";
import { render } from "react-dom";
import { updatePlaygroundQuery } from "../redux/actions/actions";
import { useSelector, useDispatch } from "react-redux";
import PlayGrounds from "./PlayGrounds";
import { useParams } from "react-router-dom";
import UpdatedPlaygroundUpdater from "./UpdatedPlaygroundUpdater";

const { Header, Content, Footer, Sider } = Layout;
const PlayGroundUpdated = () => {
  const { type, year } = useParams();

  console.log("Backend URL:", import.meta.env.VITE_REACT_APP_BACKEND_URL);

  console.log("Type ============= ", type);
  const [tableName, setTableName] = useState(null);
  const tableType = {
    PartA: year == "april2024" ? "ocr_scanned_part_a_v1" : year == "november2024" ? "ocr_scanned_part_a_v2" : '',
    PartC: year == "april2024" ? "ocr_scanned_part_c_v1" : year == "november2024" ? "ocr_scanned_part_c_v2" : '',
    Attendence: year == "april2024" ? "attendence_scanned_data" : year == "november2024" ? "attendence_scanned_data_oct" : '',
  };

  useEffect(() => {
    console.log("use effect type 123==== ", type);
    console.log("use effect table name ===== ", tableName);
    console.log("table name ==== ", tableType[type]);
    if (!tableName) {
      setTableName(tableType[type]);
    }
  }, [type, tableName]);

  const [cardData, setCardData] = useState({});
  const [responseData, setResponseData] = useState(null);
  const [totalData, setTotalData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [imageColumn, setImageColumn] = useState(null);
  const [dataFetched, setDataFetched] = useState(false);
  const [currentCardIndex, setCurrentCardIndex] = useState(0);
  const [query, setQuery] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [paginationPages, setPaginationPages] = useState(null);
  const [limit, setLimit] = useState("");
  const recordsPerPage = 50;
  const resultsContainerRef = useRef();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const reduxPlaygroundQuery = useSelector((state) => state?.playGroundQuery);
  const reduxPlaygroundPageNo = useSelector(
    (state) => state?.playGroundCurrentPage
  );
  const reduxPlaygroundTotalPages = useSelector(
    (state) => state?.playGroundtotalPages
  );
  const reduxPlaygroundResults = useSelector(
    (state) => state?.playGroundResults
  );
  console.log("Redux playground query : ", reduxPlaygroundQuery);
  console.log("Redux playground page no : ", reduxPlaygroundPageNo);
  console.log("Redux playground total pages : ", reduxPlaygroundTotalPages);
  console.log("Redux playground resutls : ", reduxPlaygroundResults);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  useEffect(() => {
    if (reduxPlaygroundQuery && !query) {
      setQuery(reduxPlaygroundQuery);
    }
  }, [reduxPlaygroundQuery]);

  useEffect(() => {
    if (reduxPlaygroundPageNo != 0 && totalPages == 0) {
      setTotalPages(reduxPlaygroundTotalPages);
    }
  }, [reduxPlaygroundTotalPages]);

  useEffect(() => {
    console.log("1234  ---- useEffect");

    if (totalData?.length == 0 && reduxPlaygroundResults) {
      console.log("Redux playground results if ...");
      console.log(
        "reduxPlaygroundResults.type === type ",
        reduxPlaygroundResults.type === type
      );
      if (reduxPlaygroundResults.type === type) {
        console.log("Into if ...");
        setTotalData(reduxPlaygroundResults?.data);
        setImageColumn("s3_path");
      }
    }
  }, [reduxPlaygroundResults]);

  useEffect(() => {
    if (currentPage == 0 && reduxPlaygroundPageNo !== 0) {
      console.log("Updating in use effect ============================= >");
      setCurrentPage(reduxPlaygroundPageNo);
    }
  }, [reduxPlaygroundPageNo]);

  const fetchQueryValue = async () => {
    // console.log("results container ref ===== ", resultsContainerRef);
    // if (resultsContainerRef) {
    //   console.log(
    //     "Results container ref current ===== ",
    //     resultsContainerRef.current
    //   );
    //   resultsContainerRef.current.innerHTML = "";
    // }
    if (query.includes("limit")) {
      alert("Please specify the limit in the input field.");
      return;
    }
    if (query.includes(";")) {
      alert("Please remove the special character from the query ';'");
      return;
    }
    if (!limit) {
      alert("Limit cannot be empty !!");
      return;
    }
    if (
      !query.includes("image_name") &&
      !query.includes("*") &&
      query.includes("ocr_scanned_part_c_v1")
    ) {
      alert(
        "Selecting primary Key (image_name) or Selecting all (*) is mandatory"
      );
      return;
    }
    if (!query.includes(tableName)) {
      alert(`This playground is only for : ${tableName}`);
      return;
    }
    setIsLoading(true);
    const payload = {
      query: query,
      limit: limit,
    };

    try {
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/fetchQueryValue`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      const data = await response.json();
      setIsLoading(false);
      if (data.status === "success") {
        setDataFetched(true);
        setTotalData(data.results);
        var tmp = {};
        tmp.type = type;
        tmp.data = data?.results;
        // dispatch(updatePlaygroundResults(data?.results));
        dispatch(updatePlaygroundResults(tmp));
        const totalPageCount = Math.ceil(data?.results.length / recordsPerPage);
        setTotalPages(totalPageCount);
        dispatch(updatePlaygroundTotalPages(totalPages));
        setCurrentPage(1);
        setResponseData(data.results.slice(0, recordsPerPage));
        const totalResults = data?.results;
        if (totalResults) {
          if (totalResults?.length > 0) {
            setCardData(totalResults[0]);
          }
        }
      } else {
        toast.error(data.message);
      }
    } catch (error) {
      console.error("Error:", error);
    }
  };

  useEffect(() => {
    dispatch(updatePlaygroundQuery(query));
  }, [query]);

  useEffect(() => {
    if (totalData) {
      if (totalData.length > 0) {
        setResponseData([]);
        console.log(" ===========================>>>>>>>>>>>>>>>>>>>>>>>> ");
        setIsLoading(true);
        setTimeout(() => {
          const startIndex = (currentPage - 1) * recordsPerPage;
          const endIndex = startIndex + recordsPerPage;
          setResponseData(totalData.slice(startIndex, endIndex));
          setIsLoading(false);
        }, 1000);
      }
      dispatch(updatePlaygroundCurrentPage(currentPage));
      renderPagination();
    }
  }, [currentPage, totalData]);

  const renderPagination = () => {
    const pages = [];
    for (let i = 1; i <= totalPages; i++) {
      pages.push(
        <span key={i}>
          {i > 1 && " | "}
          <a
            href="#!"
            onClick={() => setCurrentPage(i)}
            className={i === currentPage ? "active" : ""}
          >
            {i}
          </a>
        </span>
      );
    }
    setPaginationPages(pages);
  };

  useEffect(() => {
    renderPagination();
    dispatch(updatePlaygroundTotalPages(totalPages));
  }, [currentPage, totalPages]);

  useEffect(() => {
    console.log("current card index use effect ... ", currentCardIndex);
    if (totalData) {
      if (totalData.length > 0 && currentCardIndex < totalData.length) {
         setCardData(totalData[currentCardIndex]);
        // setIsLoading(true);
        // setTimeout(() => {
        //   setCardData(totalData[currentCardIndex]);
        //   setIsLoading(false);
        // }, 1000);
      }
    }
  }, [currentCardIndex]);

  useEffect(() => {
    if (totalData?.length > 0) {
      console.log("Result container ref ===== ", resultsContainerRef.current);
      resultsContainerRef.current.scrollIntoView();
      resultsContainerRef.current.scroll;
      // Adding a slight delay to ensure the element is rendered
      // setTimeout(() => {
      //   resultsContainerRef.current.scrollIntoView({ behavior: "smooth" });
      // }, 100);
    }
  }, [totalData]);

  const getTableData = () => {
    if (totalData.length === 0) {
      return (
        <Box className="bg-white rounded p-3 my-3 w-100 h6">
          No Results Found ...
        </Box>
      );
    }

    const keys = Object.keys(totalData[0]);

    return (
      <div className="w-100">
        <div className="my-2 overflow-auto">
          {responseData ? (
            responseData.length > 0 ? (
              <UpdatedPlaygroundUpdater
                type={type}
                tableName={tableName}
                oldData={cardData}
                currentCardIndex={currentCardIndex}
                setCurrentCardIndex={setCurrentCardIndex}
                setCardData={setCardData}
                totalData={totalData}
                s3_image_column={imageColumn}
                query={query}
              />
            ) : (
              <Box>No Results Found ...</Box>
            )
          ) : null}
        </div>
      </div>
    );
  };

  const handleSelect = (e) => {
    console.log("E ======= ", e);
    setImageColumn(e);
  };

  return (
    <AntdesignLayout>
      <div className="mx-3">
        <div className="my-3 d-flex flex-md-row flex-column">
          <div className="w-100 w-md-75">
            <QueryExecutortextArea query={query} setQuery={setQuery} />
          </div>
          <div className="d-none d-md-block w-25">
            <div className="w-100 d-flex flex-column gap-2 mx-2">
              <TextInputField
                placeholder={"limit"}
                value={limit}
                setValue={setLimit}
              />
              {totalData && totalData.length > 0 ? (
                <Select onChange={handleSelect} style={{ height: "50px" }}>
                  {Object.keys(totalData[0]).map((key) => (
                    <Select.Option key={key} value={key}>
                      {key}
                    </Select.Option>
                  ))}
                </Select>
              ) : null}

              <button
                className="btn bg-primary text-light"
                id="submit-btn"
                onClick={fetchQueryValue}
              >
                Submit
              </button>
            </div>
          </div>

          <div className="d-block d-md-none w-100">
            <div className="w-100 d-flex flex-column gap-2">
              <TextField
                className="rounded h6 bg-white"
                type="text"
                placeholder="Limit"
                id="limit-input"
                autoComplete="off"
                value={limit}
                onChange={(e) => setLimit(e.target.value)}
              />
              {totalData && totalData.length > 0 ? (
                <Select onChange={handleSelect} style={{ height: "50px" }}>
                  {Object.keys(totalData[0]).map((key) => (
                    <Select.Option key={key} value={key}>
                      {key}
                    </Select.Option>
                  ))}
                </Select>
              ) : null}

              <button
                className="btn bg-primary text-light"
                id="submit-btn"
                onClick={fetchQueryValue}
              >
                Submit
              </button>
            </div>
          </div>
        </div>
        <div
          id="results-container"
          ref={resultsContainerRef}
          className="d-flex w-100 justify-content-center"
        >
          {dataFetched && getTableData()}
        </div>
      </div>
      {isLoading && <LoadingContainer />}
    </AntdesignLayout>
  );
};

export default PlayGroundUpdated;
