import { useState, useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import { useSearchParams } from "react-router-dom";
import { Box, Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";

import AntdesignLayout from "./AntdesignLayout";
import TextInputField from "./TextInputField";
import { toast } from "react-toastify";
import LoadingContainer from "./LoadingContainer";
import SimpleDialog from "./SimpleDialog";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";
import { updatePartCErrorData, updateSystemNo } from "../redux/actions/actions";
import { updatePartCErrorList } from "../redux/actions/actions";
import { DiscFullTwoTone } from "@mui/icons-material";
import { useParams } from "react-router-dom";

const QueryCardEditor = () => {
  const {year} = useParams()
  const [searchParams, setSearchParams] = useSearchParams();
  const [barcode, setBarcode] = useState();
  const [qrcode, setQrcode] = useState();
  const [marks, setMarks] = useState(null);
  const [subjectCode, setSubjectCode] = useState(null);
  const [imageName, setImageName] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [recordData, setRecordData] = useState([]);
  const [s3Path, setS3Path] = useState(null);
  const [showDialog, setShowDialog] = useState(false);
  const [rotationResults, setRotationResults] = useState([]);
  const [rotateAngle, setRotateAngle] = useState(0);
  const evErrorsList = useSelector((state) => state?.partCErrorList);
  const table = year === "april2024" ? "ocr_scanned_part_c_v1" : year === "november2024" ? "ocr_scanned_part_c_v2" : "ocr_scanned_part_c_v1"
  const imageDomain = (year === "april2024" ? "https://docs.exampaper.vidh.ai" : (year === "november2024" ? 'https://images.exampaper.usln.in' : 'https://docs.exampaper.vidh.ai'))
  const image_name = searchParams.get("image_name");
  const paramsError = searchParams.get("error");
  const paramsErrorReason = searchParams.get("error_reason");
  const paramsSysNo = searchParams.get("sysNo");
  const paramsDegreeType = searchParams.get("degreeType");
  const [items, setItems] = useState([]);
  const [evErrorsData, setEvErrorsData] = useState([]);
  const barcodeInputRef = useRef(null);
  const qrInputRef = useRef(null);
  const marksInputRef = useRef(null);
  const subjectCodeInputRef = useRef(null);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  console.log("Ev errors list ==== ", evErrorsList);
  console.log("table is : ", table);
  // const evErrorsData = useSelector((state) => state?.partCErrorData);
  // console.log("evErrorData: ", evErrorsData);

  const fetchPrimaryKeyData = async () => {
    try {
      const payload = {
        image_name,
        table,
      };
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/fetchPrimaryKeyData`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      return await response.json();
    } catch (error) {
      throw new Error(error);
      return null;
    }
  };

  useEffect(() => {
    const marksLocalData = localStorage.getItem("marks_manual_data");
    console.log("Marks local data 123 ========= ", marksLocalData);
    if (marksLocalData) {
      console.log("Into if and updating .......");
      console.log("marks local data ==== ", marksLocalData);
      setEvErrorsData(JSON.parse(marksLocalData));
    }
  }, []);

  useEffect(() => {
    dispatch(updateSystemNo(paramsSysNo));
  }, [paramsSysNo]);

  useEffect(() => {
    console.log("Ev error data =============== ", evErrorsData);
  }, [evErrorsData]);

  useEffect(() => {
    const fetchData = async () => {
      if (table && image_name) {
        setIsLoading(true);
        const response = await fetchPrimaryKeyData();
        setIsLoading(false);
        console.log("Response is : ", response);
        if (response?.status === "success") {
          console.log("=========== Success ============");
          const data = response?.data;
          if (data.length > 0) {
            setRecordData(data[0]);
          }
        }
      }
    };
    fetchData();
    marksInputRef.current.focus()
  }, []);

  useEffect(() => {
    console.log("=========== Use effect triggered ===========");
    setBarcode(recordData?.barcode);
    setMarks(recordData?.marks);
    setQrcode(recordData?.qrcode);
    setImageName(recordData?.image_name);
    setSubjectCode(recordData?.subject_code);
    setS3Path(recordData?.s3_path);
  }, [recordData]);

  const updateRecord = async () => {
    if (!marks) {
      return;
    }
    setIsLoading(true);
    try {
      const payload = {
        qrcode,
        barcode,
        table,
        s3Path,
        subjectCode,
        marks,
        imageName,
        rotateAngle,
        year
      };
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/editPartCdata`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      const responseData = await response.json();
      setIsLoading(false);
      console.log("response data ========= ", responseData);
      if (responseData?.status === "success") {
        // toast.success("Record Updated Successfully ...");
        var currentIndex = null;
        console.log(
          "Ev errors data before filter ============= ",
          evErrorsData
        );
        var newRecords = evErrorsData.filter((data, index) => {
          if (data?.image_name === imageName) {
            currentIndex = index;
            return false;
          }
          return true;
        });
        if (!currentIndex) {
          currentIndex = 0;
        }
        console.log("new records ======1 ", newRecords);
        console.log("Current Index ===== ", currentIndex);
        dispatch(updatePartCErrorData(newRecords));
        if (newRecords.length > 0) {
          console.log("Has to navigte 12 .....");
          localStorage.setItem("marks_manual_data", JSON.stringify(newRecords));
          const newUrl = `/sections/${year}/sqlPlayground/edit?image_name=${newRecords[currentIndex]?.image_name}&error=${paramsError}&error_reason=${paramsErrorReason}&degreeType=${paramsDegreeType}&sysNo=${paramsSysNo}`;
          console.log("new url ==== ", newUrl);
          window.location.href = newUrl;
        } else {
          navigate("/");
        }
      }
    } catch (error) {
      setIsLoading(false);
      throw new Error(error);
    }
  };

  useEffect(() => {
    console.log("Rotate angle changed to ========== ", rotateAngle);
    const imageContainer = document.getElementById("img-container");
    console.log("Imge container ===== ", imageContainer);
    if (imageContainer) {
      imageContainer.style.transform = `rotate(${rotateAngle}deg)`;
    }
  }, [rotateAngle]);

  const initateRotation = async () => {
    console.log("Rotating initiated ...");
    setIsLoading(true);
    const payload = {
      imageName,
    };
    try {
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/initateRotation`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      setIsLoading(false);
      const responseData = await response.json();
      console.log("Response data ======= ", responseData);
      if (responseData?.status === "success") {
        setShowDialog(true);
        setRotationResults(responseData?.result);
      }
    } catch (error) {
      setIsLoading(false);
      throw new Error(error);
    }
  };

  const skipPage = () => {
    try {
      if (evErrorsData) {
        var currentIndex = null;
        var newRecords = evErrorsData.filter((data, index) => {
          if (data?.image_name === imageName) {
            currentIndex = index;
            return false;
          }
          return true;
        });
        if (!currentIndex) {
          currentIndex = 0;
        }
        console.log("Current Index ===== ", currentIndex);
        const newIndex = currentIndex + 1;
        console.log("new index ===== ", newIndex);
        if (newRecords.length > 0) {
          console.log("Has to navigte 12 .....");
          const newUrl = `/sections/${year}/sqlPlayground/edit?image_name=${evErrorsData[newIndex]?.image_name}&table=ocr_scanned_part_c_v1&error=${paramsError}&error_reason=${paramsErrorReason}&degreeType=${paramsDegreeType}&sysNo=${paramsSysNo}`;
          console.log("new url ==== ", newUrl);
          window.location.href = newUrl;
        }
      }
    } catch (error) {
      throw new Error(error);
    }
  };

  const handleKeyDown = (e) => {
    try {
      console.log("Handle key down clicked ...", e);
      console.log("event target ..... ", e.target);
      console.log("barcode targed .....", barcodeInputRef.current);
      if (e.key === "Enter") {
        if (e.target === barcodeInputRef.current) {
          qrInputRef.current.focus();
        } else if (e.target === qrInputRef.current) {
          marksInputRef.current.focus();
        } else if (e.target === marksInputRef.current) {
          subjectCodeInputRef.current.focus();
        } else if (e.target === subjectCodeInputRef.current) {
          updateRecord();
        }
      }
    } catch (error) {}
  };

  return (
    <AntdesignLayout>
      <Box className="d-flex justify-content-between align-items-start">
      <Box className="w-75">
          <Box className="px-5" id="img-container">
            <img
              src={`${imageDomain}/${recordData?.s3_path}`}
              width="100%"
              height="auto"
            />
          </Box>
        </Box>
        <Box className="d-flex flex-column gap-3 w-25">
          {/* {imageName && <h5 className="text-left">ID : {imageName}</h5>}
          {paramsError && (
            <h5 className="text-left">Error Code : {paramsError}</h5>
          )}
          {paramsDegreeType ? (
            paramsDegreeType === 0 ? (
              <h5 className="text-left">Degree Type : UG</h5>
            ) : (
              <h5 className="text-left">Degree Type : PG</h5>
            )
          ) : null} */}
           <h5 style={{textAlign:"left",marginTop:'10px',marginBottom:'0px'}}><strong>COVER CODE : </strong>{recordData?.new_cover_barcode}</h5>
          <TextInputField
            placeholder="Barcode"
            value={barcode}
            setValue={setBarcode}
            onKeyDown={handleKeyDown}
            ref={barcodeInputRef}
          />
          <TextInputField
            placeholder="QR Code"
            value={qrcode}
            setValue={setQrcode}
            onKeyDown={handleKeyDown}
            ref={qrInputRef}
          />
          <TextInputField
            placeholder="Marks"
            value={marks}
            setValue={setMarks}
            onKeyDown={handleKeyDown}
            ref={marksInputRef}
          />
          <TextInputField
            placeholder="Subject Code"
            value={subjectCode}
            setValue={setSubjectCode}
            onKeyDown={handleKeyDown}
            ref={subjectCodeInputRef}
          />
          <Button
            className="bg-primary text-white rounded p-3"
            onClick={() => {
              updateRecord();
            }}
          >
            Update
          </Button>
          <Button
            className="bg-primary text-white rounded p-3"
            onClick={() => {
              skipPage();
            }}
          >
            Skip
          </Button>
          <Box className="d-flex justify-content-between">
            <Button
              className="bg-primary text-white rounded p-3"
              onClick={() => setRotateAngle((prev) => prev - 90)}
            >
              Rotate <RotateLeftIcon />
            </Button>
            <Button
              className="bg-primary text-white rounded p-3"
              onClick={() => setRotateAngle((prev) => prev + 90)}
            >
              Rotate <RotateRightIcon />
            </Button>
          </Box>
        </Box>
      </Box>
      {isLoading && <LoadingContainer />}
      {showDialog && (
        <SimpleDialog
          type="rotation_results"
          rotationResults={rotationResults}
          setShowDialog={setShowDialog}
        />
      )}
    </AntdesignLayout>
  );
};

export default QueryCardEditor;
