import React, { useState,useRef } from "react";
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Breadcrumb, Layout, Menu, Typography, theme } from "antd";
import { Box, Button } from "@mui/material";
import { useEffect } from "react";
import TextField from "@mui/material/TextField";
import EditButton from "./EditButton";
import { width } from "@mui/system";
import { ToastContainer, toast } from "react-toastify";
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 { useSelector, useDispatch } from "react-redux";
import {
  updatePartAanomolyData,
  updateSystemNo,
} from "../redux/actions/actions";
import SimpleDialog from "./SimpleDialog";
import SystemNumberDialog from "./SystemNumberDialog";
import ValidationContainer from "./ValidationContainer";

const { Header, Content, Footer, Sider } = Layout;
function getItem(label, key, icon, children) {
  return {
    key,
    icon,
    children,
    label,
  };
}
// const items = [
//   getItem('Option 1', '1', <PieChartOutlined />),
//   getItem('Option 2', '2', <DesktopOutlined />),
//   getItem('User', 'sub1', <UserOutlined />, [
//     getItem('Tom', '3'),
//     getItem('Bill', '4'),
//     getItem('Alex', '5'),
//   ]),
//   getItem('Team', 'sub2', <TeamOutlined />, [getItem('Team 1', '6'), getItem('Team 2', '8')]),
//   getItem('Files', '9', <FileOutlined />),
// ];

const items = [getItem("Reassigned Booklet No", "1", <PieChartOutlined />)];

const PartACorrection = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [barcodeInput, setBarcodeInput] = useState(null);
  const [dataFetched, setDataFetched] = useState(false);
  const [studentData, setStudentData] = useState(null);
  const [updateReassigned, setUpdateReassigned] = useState(false);
  const [reasssingedSno, setReassignedSno] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [scaleWidthValue, setScaleWidthValue] = useState(80);
  const [rotateValue, setRotateValue] = useState(0);
  const navigate = useNavigate();
  let [searchParams, setSearchParams] = useSearchParams();
  const searchParamsBarcode = searchParams.get("barcode");
  const batchType = searchParams.get("batchType");
  const s3Path = searchParams.get("s3Path");
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);
  const [backgroundPosition, setBackgroundPosition] = useState("0% 0%");
  const [zoomed, setZoomed] = useState(false);
  const [correctedRegisterNo, setCorrectedRegisterNo] = useState(null);
  const [correctedAnswerBookletNo, setCorrectedAnswerBookletNo] =
    useState(null);
  const [correctedSubjectCode, setCorrectedSubjectCode] = useState(null);
  const [correctedSerialNo, setCorrectedSerialNo] = useState(null);
  const [correctedExamDate, setCorrectedExamDate] = useState(null);
  const [correctedCandidateName, setCorrectedCandidateName] = useState(null);
  const [correctedExamCentreCode, setCorrectedExamCentreCode] = useState(null);
  const [correctedBarcodeNo, setCorrectedBarcodeNo] = useState(null);
  const [correctedSubjectTitle, setCorrectedSubjectTitle] = useState(null);
  const [showSubjectTitleInput, setShowSubjectTitleInput] = useState(false);
  const [showAdditionalStudentInputs, setShowAdditionalStudentInputs] =
    useState(false);
  const [fallbackText, setFallBackText] = useState(null);
  const [showDialogBox, setShowDialogBox] = useState(false);
  const [dialogBoxConsent, setDialogBoxConsent] = useState(null);
  const [dialogText, setDialogText] = useState(null);
  const [metaBaseSubjectLinkWithTitle, setMetaBaseSubjectLinkWithTitle] =
    useState(null);
  const [metaBaseSubjectLinkWithoutTitle, setMetaBaseSubjectLinkWithoutTitle] =
    useState(null);
  const [metaBaseRegnoLink, setMetaBaseRegnoLink] = useState(null);
  const reduxSystemNo = useSelector((state) => state?.systemNumber);
  const systemNo = searchParams.get("sysNo");
  const [showSystemNoContainer, setShowSystemNoContainer] = useState(false);
  const [validateContainerData, setValidateContainerData] = useState([]);
  const [showValidationContainer, setShowValidationContainer] = useState(false);


  const subjectCodeInputRef = useRef(null);
  const examcentreCodeInputRef = useRef(null);
  const examDateInputRef = useRef(null);
  const studentNameInputRef = useRef(null);
  const bookletInputRef = useRef(null);
  const registerNumberInputRef = useRef(null);

  // Handle the Enter key press in the register number input
  const handleRegisterNumberKeyDown = (e) => {
    console.log("Handle register number key down ....")
    if (e.key === 'Enter') {
      console.log("Entering subject code field ...")
      // Focus on the subject code input
      registerNumberInputRef.current.unfocus()
      const subjectCodeInput = subjectCodeInputRef.current;
      console.log("Subject code input :: ",subjectCodeInput)
      subjectCodeInput.focus();
      subjectCodeInput.select();
    }
  };

  const handleBookletSerialNoKeyDown = (e) =>{
    console.log("Handdle booklet serial no key down.....")
    if(e.key === 'Enter'){
      console.log("Entering register number field...")
      const registerNumberInputField = registerNumberInputRef.current
      console.log("Register number input :: ",registerNumberInputField)
      registerNumberInputField.focus()
      // const ele = document.getElementById("corrected-register-number-input")
      // console.log("ELE : ",ele)
      // ele.focus()
    }
  }


  const dispatch = useDispatch();
  useEffect(() => {
    if (!reduxSystemNo && !systemNo) {
      setShowSystemNoContainer(true);
    } else {
      dispatch(updateSystemNo(systemNo));
      fetchAnomalyData();
    }
  }, [reduxSystemNo]);

  useEffect(() => {
    if (batchType === "old") {
      setShowAdditionalStudentInputs(true);
    }
  }, []);

  const reduxPartA2023AnomolyData = useSelector(
    (state) => state.partABatchAnomolyData
  );
  // console.log("Redux partA 2023 anomoly data : ",reduxPartA2023AnomolyData)

  const handleMouseMove = (e) => {
    const { left, top, width, height } = e.target.getBoundingClientRect();
    const x = ((e.pageX - left) / width) * 100;
    const y = ((e.pageY - top) / height) * 100;
    setBackgroundPosition(`${x}% ${y}%`);
    setZoomed(true);
  };

  useEffect(() => {
    const handleResize = () => {
      setWindowWidth(window.innerWidth);
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  useEffect(() => {
    if (windowWidth < 800) {
      setCollapsed(true);
    }
    if (windowWidth > 800) {
      setCollapsed(false);
    }
  }, [windowWidth]);

  useEffect(() => {
    if (searchParamsBarcode) {
      setBarcodeInput(searchParamsBarcode);
    }
  }, [searchParamsBarcode]);

  useEffect(() => {
    submitbarcodeInput();
  }, [barcodeInput]);

  const url = `https://docs.exampaper.vidh.ai/${studentData?.s3_path}`;
  const figureStyle = {
    backgroundImage: `url(${url})`,
    backgroundPosition: zoomed ? backgroundPosition : "center",
    backgroundSize: zoomed ? "200%" : "cover",
    height: "100%", // Adjust the height as needed
    width: "90%", // Adjust the width as needed
    border: "1px solid #ddd",
    overflow: "hidden",
  };

  const handleMouseLeave = () => {
    setBackgroundPosition("0% 0%");
    setZoomed(false);
  };

  function getRecordsBySystemId(records, systemId) {
    const new_data = [];
    for (var i = 0; i < records.length; i++) {
      var count = i % 5;
      if (count === systemId - 1) {
        new_data.push(records[i]);
      }
    }
    return new_data;
  }

  useEffect(() => {
    console.log("Show additional inputs : ", showAdditionalStudentInputs);
  }, [showAdditionalStudentInputs]);

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const validateData = () => {
    setIsLoading(true);
    try {
      const payload = {
        correctedRegisterNo,
        correctedSubjectCode,
      };
      fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/validateStudentData`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      )
        .then((response) => response.json())
        .then((responseData) => {
          setIsLoading(false);
          if (responseData.status === "success") {
            setValidateContainerData(responseData?.data);
            if ((responseData?.data).length === 0) {
              setShowAdditionalStudentInputs(true);
            } else {
              if (batchType !== "old") {
                setShowAdditionalStudentInputs(false);
              }
            }
            setShowValidationContainer(true);
          } else {
            toast.error("Something Went Wrong !!");
          }
        });
    } catch (error) {
      throw new Error(error);
    }
  };

  const fetchAnomalyData = () => {
    setFallBackText(null);
    console.log("Fetching.......");
    setIsLoading(true);
    fetch(
      `${
        import.meta.env.VITE_REACT_APP_BACKEND_URL
      }/fetchAnamolyPartAData?type=${batchType}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      }
    )
      .then((response) => {
        console.log("Response fetched..");
        return response.json();
      })
      .then((responseData) => {
        console.log("Response Data is : ", responseData);
        setIsLoading(false);
        if (responseData.status === "success") {
          const systemRecords = getRecordsBySystemId(
            responseData?.data,
            reduxSystemNo
          );
          console.log("System records : ", systemRecords);
          // setAnomolyData(systemRecords);
          dispatch(updatePartAanomolyData(systemRecords));
          dispatch(updatePartAanomolyData(responseData?.data));
          if ((responseData?.data).length == 0) {
            setFallBackText("No Data Found !!");
          }
        }
      })
      .catch((error) => {
        console.error("Error fetching data: ", error);
        setIsLoading(false);
      });
  };

  useEffect(() => {
    // console.log("12345 Useeffect called");
    console.log("Consent is : ", dialogBoxConsent);
    // console.log("Dialog text before if condition :: ",dialogText)
    // console.log("showDialog Box : ",showDialogBox)
    if (dialogBoxConsent == "No" && !showDialogBox) {
      console.log("Consent is NO");
      var index = 0;
      var RecordIndex = 0;
      var localStoragePartAanomoly = [];
      if (batchType === "old") {
        localStoragePartAanomoly = localStorage.getItem("part-a-old-anomoly");
        console.log(
          "localstorage parta anomoly : ",
          JSON.parse(localStoragePartAanomoly)
        );
        if (localStoragePartAanomoly) {
          localStoragePartAanomoly = JSON.parse(localStoragePartAanomoly);
        }
      } else if (batchType !== "old") {
        localStoragePartAanomoly = localStorage.getItem("part-a-anomoly");
        console.log(
          "localstorage parta anomoly : ",
          JSON.parse(localStoragePartAanomoly)
        );
        if (localStoragePartAanomoly) {
          localStoragePartAanomoly = JSON.parse(localStoragePartAanomoly);
        }
      }
      console.log(
        "Length of redux data >>>>>>>>>>>>>>>>>>>>> ",
        localStoragePartAanomoly.length
      );
      const filteredData = localStoragePartAanomoly.filter((data) => {
        console.log("S3path : ", s3Path);
        if (data?.s3_path == s3Path) {
          RecordIndex = index;
          console.log("data matched : ", data);
          return false; // Return false to remove the matched item
        }
        index += 1;
        return true; // Keep the unmatched items
      });
      console.log("RecordIndex is : ", RecordIndex);
      console.log("Lenght of filtered Data >>>>>>>>>>> ", filteredData.length);
      console.log("Filtered Data Part A: ", filteredData);
      dispatch(updatePartAanomolyData(filteredData));
      if (batchType === "old") {
        localStorage.setItem(
          "part-a-old-anomoly",
          JSON.stringify(filteredData)
        );
      } else if (batchType !== "old") {
        localStorage.setItem("part-a-anomoly", JSON.stringify(filteredData));
      }
      if (filteredData.length > 0) {
        console.log("navigating ...", filteredData[RecordIndex].s3_path);
        setDialogBoxConsent(null);
        const navigationLink = `/anomoly/partA/booklet?batchType=${batchType}&barcode=${filteredData[RecordIndex].barcode}&s3Path=${filteredData[RecordIndex].s3_path}&sysNo=${reduxSystemNo}`;
        console.log("Navigation link123 : ", navigationLink);
        // navigate(navigationLink);
        window.location.href = navigationLink;
      } else {
        toast.success("All Records Are Updated ....");
        navigate("/");
      }
    } else if (dialogBoxConsent == "Yes" && !showDialogBox) {
      if (dialogText) {
        const lowerCaseDialogText = dialogText.toLowerCase();
        console.log("Lower case dialog text :: ", lowerCaseDialogText);
        if (
          lowerCaseDialogText.includes("registration") &&
          !lowerCaseDialogText.includes("subject")
        ) {
          console.log("Register number not found");
          setShowAdditionalStudentInputs(true);
          setMetaBaseRegnoLink(
            "https://metabase.usln.in/public/question/8f4aaf13-7cee-4378-bfb7-1635b6ae8265"
          );
        } else if (
          lowerCaseDialogText.includes("registration") &&
          lowerCaseDialogText.includes("subject")
        ) {
          setShowSubjectTitleInput(true);
          setShowAdditionalStudentInputs(true);
          console.log("Both register number and subject code not found");
          setMetaBaseSubjectLinkWithTitle(
            "https://metabase.usln.in/public/question/65dee651-0b18-4f07-b992-48b07d74f2c9"
          );
          setMetaBaseSubjectLinkWithoutTitle(
            "https://metabase.usln.in/public/question/3175d0f2-b292-42ec-a72f-41382d442879"
          );
          setMetaBaseRegnoLink(
            "https://metabase.usln.in/public/question/8f4aaf13-7cee-4378-bfb7-1635b6ae8265"
          );
        } else if (
          lowerCaseDialogText.includes("subject") &&
          !lowerCaseDialogText.includes("registration")
        ) {
          setShowSubjectTitleInput(true);
          console.log("Subject Code not found");
          setMetaBaseSubjectLinkWithTitle(
            "https://metabase.usln.in/public/question/65dee651-0b18-4f07-b992-48b07d74f2c9"
          );
          setMetaBaseSubjectLinkWithoutTitle(
            "https://metabase.usln.in/public/question/3175d0f2-b292-42ec-a72f-41382d442879"
          );
        }
      }
      const container = document.getElementById("iframe-container");
      if (container) {
        console.log("Container found");
        setTimeout(function () {
          console.log("Scrolling....");
          container.scrollIntoView();
        }, 1000); // 2000 milliseconds = 2 seconds
      }
    }
  }, [dialogBoxConsent, setDialogBoxConsent, showDialogBox]);

  const submitbarcodeInput = async () => {
    setIsLoading(true);
    setStudentData(null);
    if (!barcodeInput) {
      console.log("Returning");
      return;
    }
    const payload = {
      barcodeInput,
      s3Path,
    };
    const response = await fetch(
      `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/fetchBarcodeInfo`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      }
    );
    const responseData = await response.json();
    console.log("Response Data is : ", responseData);
    setDataFetched(true);
    setIsLoading(false);
    if (responseData.status === "success") {
      console.log("Into top if");
      if (!responseData.data) {
        setStudentData(null);
      }
      if (responseData.data) {
        console.log("Students Data :", responseData.data[0]);
        setStudentData(responseData.data[0]);
        const students_data = responseData.data[0];
        setCorrectedRegisterNo(students_data?.register_number);
        setCorrectedSubjectCode(students_data?.subject_code);
        setCorrectedSerialNo(students_data?.slno);
      }
    }
    if (reduxPartA2023AnomolyData.length == 0) {
      fetchAnomalyData();
    }
  };

  const updatePartAanomoly = async (e) => {
    subjectCodeInputRef.current.blur()
    setIsLoading(true);
    setMetaBaseRegnoLink(null);
    setMetaBaseSubjectLinkWithTitle(null);
    setMetaBaseSubjectLinkWithoutTitle(null);
    const s3_path = studentData?.s3_path;
    const payload = {
      batchType,
      s3_path,
      barcodeInput,
      correctedRegisterNo,
      correctedSubjectCode,
      correctedBarcodeNo,
      correctedCandidateName,
      correctedExamDate,
      correctedSerialNo,
      correctedExamCentreCode,
      correctedSubjectTitle,
    };
    const response = await fetch(
      `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/updatePartAanomoly`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      }
    );
    const responseData = await response.json();
    setIsLoading(false);
    if (
      responseData?.status === "success" &&
      responseData?.status_code == 200
    ) {
      toast.success(responseData?.message);
      var index = 0;
      var RecordIndex = 0;
      console.log(
        "length of redux data >>>>>>>>>>>>>> ",
        reduxPartA2023AnomolyData.length
      );
      var localStoragePartAanomoly = [];
      if (batchType === "old") {
        localStoragePartAanomoly = localStorage.getItem("part-a-old-anomoly");
        console.log(
          "localstorage parta anomoly : ",
          JSON.parse(localStoragePartAanomoly)
        );
        if (localStoragePartAanomoly) {
          localStoragePartAanomoly = JSON.parse(localStoragePartAanomoly);
        }
      } else if (batchType !== "old") {
        localStoragePartAanomoly = localStorage.getItem("part-a-anomoly");
        console.log(
          "localstorage parta anomoly : ",
          JSON.parse(localStoragePartAanomoly)
        );
        if (localStoragePartAanomoly) {
          localStoragePartAanomoly = JSON.parse(localStoragePartAanomoly);
        }
      }
      const filteredData = localStoragePartAanomoly.filter((data) => {
        console.log("S3path : ", s3Path);
        if (data?.s3_path == s3Path) {
          RecordIndex = index;
          console.log("data matched : ", data);
          return false; // Return false to remove the matched item
        }
        index += 1;
        return true; // Keep the unmatched items
      });
      console.log("Record Index is : ", RecordIndex);
      console.log("Filtered Data Part A: ", filteredData);
      console.log(
        "Filtered array length >>>>>>>>>>>>>>>>>>>> ",
        filteredData.length
      );
      dispatch(updatePartAanomolyData(filteredData));
      if (batchType === "old") {
        localStorage.setItem(
          "part-a-old-anomoly",
          JSON.stringify(filteredData)
        );
      } else if (batchType !== "old") {
        localStorage.setItem("part-a-anomoly", JSON.stringify(filteredData));
      }
      if (filteredData.length > 0) {
        console.log("navigating ...", filteredData[RecordIndex].s3_path);
        setDialogBoxConsent(null);
        const navigationLink = `/anomoly/partA/booklet?batchType=${batchType}&barcode=${filteredData[RecordIndex].barcode}&s3Path=${filteredData[RecordIndex].s3_path}&sysNo=${reduxSystemNo}`;
        console.log("Navigation link123 : ", navigationLink);
        // navigate(navigationLink);
        window.location.href = navigationLink;
      } else {
        toast.success("All Records Are Updated ....");
        navigate("/");
      }
    } else if (responseData?.status_code == 500) {
      toast.error("Something Went Wrong !!");
    } else if (
      responseData?.status === "success" &&
      responseData?.status_code == 205
    ) {
      setShowDialogBox(true);

      setDialogText(responseData?.missing_data);
    }
  };

  const ZoomInImage = () => {
    console.log("Zooming In Image ....");
    const elements = document.getElementsByClassName("scanned-img");
    for (var ele of elements) {
      console.log("Ele is : ", ele);
      const newScaleWidthValue = scaleWidthValue + 10;
      setScaleWidthValue(newScaleWidthValue);
      // ele.style.transform = `scale(${newScaleValue})`;
      ele.style.width = `${newScaleWidthValue}%`;
    }
  };

  const ZoomOutImage = () => {
    console.log("Zooming Out Image ....");
    const elements = document.getElementsByClassName("scanned-img");
    for (var ele of elements) {
      console.log("Ele is : ", ele);
      const newScaleWidthValue = scaleWidthValue - 10;
      setScaleWidthValue(newScaleWidthValue);
      // ele.style.transform = `scale(${newScaleValue})`;
      ele.style.width = `${newScaleWidthValue}%`;
    }
  };

  const RotateImageLeft = () => {
    const elements = document.getElementsByClassName("scanned-img");
    for (var ele of elements) {
      console.log("Ele is : ", ele);
      const newRotateValue = rotateValue - 90;
      setRotateValue(newRotateValue);
      ele.style.transform = `rotate(${newRotateValue}deg)`;
    }
  };

  const RotateImageRight = () => {
    const elements = document.getElementsByClassName("scanned-img");
    for (var ele of elements) {
      console.log("Ele is : ", ele);
      const newRotateValue = rotateValue + 90;
      setRotateValue(newRotateValue);
      ele.style.transform = `rotate(${newRotateValue}deg)`;
    }
  };

  const handleKeyDown = (event) => {
    console.log("Handling key down ...");
    if (event.key === "Enter") {
      console.log("Enter pressed ...");
      updatePartAanomoly(event);
    }
  };

  const handleSystemNoChange = () => {
    console.log("System No Change is called");
    setShowSystemNoContainer(true);
  };

  return (
    <Layout
      style={{
        minHeight: "100vh",
      }}
    >
      <ToastContainer />
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
      >
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          defaultSelectedKeys={["1"]}
          mode="inline"
          items={items}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: 0,
            background: colorBgContainer,
          }}
        >
          {fallbackText && <h4>{fallbackText}</h4>}
          {showDialogBox && (
            <SimpleDialog
              dialogBoxConsent={dialogBoxConsent}
              setDialogBoxConsent={setDialogBoxConsent}
              showDialogBox={showDialogBox}
              setShowDialogBox={setShowDialogBox}
              dialogText={dialogText}
              batchType={batchType}
            />
          )}
          <Box className="d-flex justify-content-between h-100 py-1 px-2">
            <Button
              className="bg-primary p-md-1 p-0 text-light"
              onClick={() => {
                navigate(-1);
              }}
            >
              <ArrowBackIcon />
            </Button>
            <Box className="d-flex justify-content-between h-100 gap-md-4 gap-1">
              {reduxSystemNo && (
                <Box
                  className="h6 p-0 m-0 text-light bg-primary rounded h-100 d-flex align-items-center px-3"
                  style={{ cursor: "pointer" }}
                  onClick={handleSystemNoChange}
                >
                  <b>System No : </b> {reduxSystemNo}
                </Box>
              )}
              <Box className="d-flex justify-content-between gap-2">
                <Button
                  className="bg-primary p-1 text-light"
                  onClick={() => {
                    navigate("/");
                  }}
                >
                  <HomeIcon />
                </Button>
              </Box>
            </Box>
          </Box>
        </Header>
        <Content
          style={{
            margin: "16px 16px",
          }}
        >
          <Box className="w-100 d-flex flex-column flex-md-row justify-content-between">
            <Box className="w-25 d-none d-md-flex flex-column">
              <Box className="d-flex justify-content-start flex-column align-items-start mx-2">
                <label for="barcode" className="h6">
                  <u>OCR Barcode:</u>
                </label>
                <h5 name="barcode">{barcodeInput}</h5>
              </Box>
              {!isLoading && !studentData && (
                <Box className="w-100 py-5">
                  <h6>Invalid Booklet Serial No !!</h6>
                </Box>
              )}
              {dataFetched && studentData && (
                <>
                  <Box>
                    <Box className="px-2">
                      {batchType != "old" && (
                        <Box className="d-flex flex-column align-items-start gap-2 py-2">
                          <label for="student-name-input" className="h6">
                            <u>OCR Booklet No:</u>
                          </label>
                          <h5 className="text-break">
                            {studentData?.booklet_serial_no}
                          </h5>
                        </Box>
                      )}
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="student-name-input" className="h6">
                          <u>OCR Register Number:</u>
                        </label>
                        <h5 className="text-break">
                          {studentData?.register_number}
                        </h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-code-input" className="h6">
                          <u>OCR Subject Code:</u>
                        </label>
                        <h5 className="text-break">
                          {studentData?.subject_code}
                        </h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-input" className="h6">
                          <u>Type:</u>
                        </label>
                        <h5>{studentData?.type}</h5>
                      </Box>
                      {
                        <>
                          {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                            <label for="corrected-register-number-input">
                              Corrected Barcode Number:
                            </label>
                            <Box className="d-flex justify-content-between w-100">
                              <TextField
                                id="corrected-register-number-input"
                                className="w-100"
                                value={correctedBarcodeNo}
                                autoComplete="off"
                                onChange={(e) => {
                                  setCorrectedBarcodeNo(e.target.value);
                                }}
                              />
                            </Box>
                          </Box> */}
                          {/* {showSubjectTitleInput && (
                            <Box className="d-flex flex-column align-items-start gap-2 py-2">
                              <label for="corrected-register-number-input">
                                Corrected Subject Title:
                              </label>
                              <Box className="d-flex justify-content-between w-100">
                                <TextField
                                  id="corrected-register-number-input"
                                  className="w-100"
                                  value={correctedSubjectTitle}
                                  autoComplete="off"
                                  onChange={(e) => {
                                    correctedSubjectTitle(e.target.value);
                                  }}
                                />
                              </Box>
                            </Box>
                          )} */}
                          {showAdditionalStudentInputs && (
                            <>
                              {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Exam Centre Code:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedExamCentreCode}
                                    inputRef={examcentreCodeInputRef}
                                    autoComplete="off"
                                    onChange={(e) => {
                                      setCorrectedExamCentreCode(
                                        e.target.value
                                      );
                                    }}
                                  />
                                </Box>
                              </Box> */}
                              {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Exam Date:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedExamDate}
                                    autoComplete="off"
                                    inputRef = {examDateInputRef}
                                    onChange={(e) => {
                                      setCorrectedExamDate(e.target.value);
                                    }}
                                    placeholder="(DD-MM-YYYY)"
                                  />
                                </Box>
                              </Box> */}
                              {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Student Name:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedCandidateName}
                                    inputRef = {studentNameInputRef}
                                    autoComplete="off"
                                    onChange={(e) => {
                                      setCorrectedCandidateName(e.target.value);
                                    }}
                                  />
                                </Box>
                              </Box> */}
                              {batchType === "old" && (
                                <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                  <label for="corrected-register-number-input">
                                    Corrected Booklet Serial No:
                                  </label>
                                  <Box className="d-flex justify-content-between w-100">
                                    <TextField
                                      id="corrected-register-number-input"
                                      className="w-100"
                                      value={correctedSerialNo}
                                      inputRef={bookletInputRef}
                                      autoComplete="off"
                                      onKeyDown={handleBookletSerialNoKeyDown}
                                      onChange={(e) => {
                                        setCorrectedSerialNo(e.target.value);
                                      }}
                                    />
                                  </Box>
                                </Box>
                              )}
                            </>
                          )}
                        </>
                      }
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="corrected-register-number-input">
                          Corrected Student Register Number:
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="corrected-register-number-input"
                            className="w-100"
                            value={correctedRegisterNo}
                            inputRef={registerNumberInputRef}
                            autoComplete="off"
                            onKeyDown={handleRegisterNumberKeyDown} // Attach the keydown handler
                            onChange={(e) => {
                              setCorrectedRegisterNo(e.target.value);
                            }}
                          />
                        </Box>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="corrected-student-code-input">
                          Corrected Subject Code:
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="corrected-student-code-input"
                            className="w-100"
                            value={correctedSubjectCode}
                            // onMouseLeave={()=>{
                            //   if(correctedRegisterNo && correctedSubjectCode){
                            //     validateData()
                            //   }
                            // }}
                            autoComplete="off"
                            onKeyDown={handleKeyDown}
                            inputRef={subjectCodeInputRef}
                            onChange={(e) => {
                              setCorrectedSubjectCode(e.target.value);
                            }}
                          />
                        </Box>
                      </Box>
                      <Box className="py-2 d-flex flex-column gap-2 justify-content-start">
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          onClick={validateData}
                        >
                          Validate
                        </Button>
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          onClick={updatePartAanomoly}
                        >
                          Update
                        </Button>
                      </Box>
                    </Box>
                  </Box>
                </>
              )}
            </Box>
            <Box className="w-md-25 d-flex d-md-none flex-column">
              <Box className="d-flex justify-content-start flex-column mx-2 align-items-start">
                <label for="barcode" className="h6">
                  <u>Barcode:</u>
                </label>
                <h5 name="barcode">{barcodeInput}</h5>
              </Box>
              {!isLoading && !studentData && (
                <Box className="w-100 py-5">
                  <h6>Invalid Booklet Serial No !!</h6>
                </Box>
              )}
              {dataFetched && studentData && (
                <>
                  <Box>
                    <Box className="px-2">
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="student-name-input" className="h6">
                          <u>OCR Register Number:</u>
                        </label>
                        <h5 className="text-break">
                          {studentData?.register_number}
                        </h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-code-input" className="h6">
                          <u>OCR Subject Code:</u>
                        </label>
                        <h5 className="text-break">
                          {studentData?.subject_code}
                        </h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-input" className="h6">
                          <u>Type:</u>
                        </label>
                        <h5>{studentData?.type}</h5>
                      </Box>
                      {
                        <>
                          {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                            <label for="corrected-register-number-input">
                              Corrected Barcode Number:
                            </label>
                            <Box className="d-flex justify-content-between w-100">
                              <TextField
                                id="corrected-register-number-input"
                                className="w-100"
                                value={correctedBarcodeNo}
                                autoComplete="off"
                                onChange={(e) => {
                                  setCorrectedBarcodeNo(e.target.value);
                                }}
                              />
                            </Box>
                          </Box> */}
                          {/* {showSubjectTitleInput && (
                            <Box className="d-flex flex-column align-items-start gap-2 py-2">
                              <label for="corrected-register-number-input">
                                Corrected Subject Title:
                              </label>
                              <Box className="d-flex justify-content-between w-100">
                                <TextField
                                  id="corrected-register-number-input"
                                  className="w-100"
                                  value={correctedSubjectTitle}
                                  autoComplete="off"
                                  onChange={(e) => {
                                    correctedSubjectTitle(e.target.value);
                                  }}
                                />
                              </Box>
                            </Box>
                          )} */}
                          {showAdditionalStudentInputs && (
                            <>
                              {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Exam Centre Code:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedExamCentreCode}
                                    autoComplete="off"
                                    onChange={(e) => {
                                      setCorrectedExamCentreCode(
                                        e.target.value
                                      );
                                    }}
                                  />
                                </Box>
                              </Box>
                              <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Exam Date:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedExamDate}
                                    autoComplete="off"
                                    onChange={(e) => {
                                      setCorrectedExamDate(e.target.value);
                                    }}
                                    placeholder="(DD-MM-YYYY)"
                                  />
                                </Box>
                              </Box>
                              <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Student Name:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedCandidateName}
                                    autoComplete="off"
                                    onChange={(e) => {
                                      setCorrectedCandidateName(e.target.value);
                                    }}
                                  />
                                </Box>
                              </Box> */}
                              <Box className="d-flex flex-column align-items-start gap-2 py-2">
                                <label for="corrected-register-number-input">
                                  Corrected Booklet Serial No:
                                </label>
                                <Box className="d-flex justify-content-between w-100">
                                  <TextField
                                    id="corrected-register-number-input"
                                    className="w-100"
                                    value={correctedSerialNo}
                                    onKeyDown={handleBookletSerialNoKeyDown}
                                    autoComplete="off"
                                    onChange={(e) => {
                                      setCorrectedSerialNo(e.target.value);
                                    }}
                                  />
                                </Box>
                              </Box>
                            </>
                          )}
                        </>
                      }
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="corrected-register-number-input">
                          Corrected Student Register Number:
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="corrected-register-number-input"
                            className="w-100"
                            value={correctedRegisterNo}
                            autoComplete="off"
                            inputRef={registerNumberInputRef}
                            onKeyDown={handleRegisterNumberKeyDown}
                            onChange={(e) => {
                              setCorrectedRegisterNo(e.target.value);
                            }}
                          />
                        </Box>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="corrected-student-code-input">
                          Corrected Subject Code:
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="corrected-student-code-input"
                            className="w-100"
                            value={correctedSubjectCode}
                            autoComplete="off"
                            onKeyDown={handleKeyDown}
                            onChange={(e) => {
                              setCorrectedSubjectCode(e.target.value);
                            }}
                          />
                        </Box>
                      </Box>
                      <Box className="py-2 d-flex flex-column gap-2 justify-content-start">
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          onClick={validateData}
                        >
                          Validate
                        </Button>
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          onClick={updatePartAanomoly}
                        >
                          Update
                        </Button>
                      </Box>
                    </Box>
                  </Box>
                </>
              )}
            </Box>
            <Box
              className="w-75 d-none d-md-block overflow-auto"
              style={{ height: "800px", overflow: "auto" }}
            >
              {studentData && (
                <Box className="py-2">
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={ZoomInImage}
                  >
                    ZoomIn
                  </Button>
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={ZoomOutImage}
                  >
                    ZoomOut
                  </Button>
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={RotateImageLeft}
                  >
                    <RotateLeftIcon />
                  </Button>
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={RotateImageRight}
                  >
                    <RotateRightIcon />
                  </Button>
                </Box>
              )}
              {studentData && (
                <>
                  <Box className="overflow-auto">
                    <img
                      className="scanned-img"
                      src={`https://docs.exampaper.vidh.ai/${studentData?.s3_path}`}
                      width={`${scaleWidthValue}%`}
                    />
                  </Box>
                  <Box id="iframe-container" className="my-2">
                    {metaBaseSubjectLinkWithTitle && (
                      <Box>
                        <iframe
                          width="1000px"
                          height="800px"
                          src={metaBaseSubjectLinkWithTitle}
                        />
                      </Box>
                    )}
                    {metaBaseSubjectLinkWithoutTitle && (
                      <Box>
                        <iframe
                          width="1000px"
                          height="800px"
                          src={metaBaseSubjectLinkWithoutTitle}
                        />
                      </Box>
                    )}
                    {metaBaseRegnoLink && (
                      <Box>
                        <iframe
                          width="1000px"
                          height="800px"
                          src={metaBaseRegnoLink}
                        />
                      </Box>
                    )}
                  </Box>
                </>
              )}
            </Box>
            <Box className="w-100 d-md-none overflow-auto">
              {studentData && (
                <Box className="py-2">
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={ZoomInImage}
                  >
                    ZoomIn
                  </Button>
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={ZoomOutImage}
                  >
                    ZoomOut
                  </Button>
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={RotateImageLeft}
                  >
                    <RotateLeftIcon />
                  </Button>
                  <Button
                    className="bg-primary text-light p-3 mx-1"
                    onClick={RotateImageRight}
                  >
                    <RotateRightIcon />
                  </Button>
                </Box>
              )}
              {studentData && (
                <>
                  <Box className="overflow-auto">
                    <img
                      className="scanned-img"
                      src={`https://docs.exampaper.vidh.ai/${studentData.s3_path}`}
                      width={`${scaleWidthValue}%`}
                    />
                  </Box>
                  <Box id="iframe-container" className="my-2">
                    {metaBaseSubjectLinkWithTitle && (
                      <Box>
                        <iframe
                          width="1000px"
                          height="800px"
                          src={metaBaseSubjectLinkWithoutTitle}
                        />
                      </Box>
                    )}
                    {metaBaseSubjectLinkWithoutTitle && (
                      <Box>
                        <iframe
                          width="1000px"
                          height="800px"
                          src={metaBaseSubjectLinkWithTitle}
                        />
                      </Box>
                    )}
                    {metaBaseRegnoLink && (
                      <Box>
                        <iframe
                          width="1000px"
                          height="800px"
                          src={metaBaseRegnoLink}
                        />
                      </Box>
                    )}
                  </Box>
                </>
              )}
            </Box>
          </Box>
        </Content>
        <Footer
          style={{
            textAlign: "center",
          }}
        >
          exampaper.vidh.ai ©{new Date().getFullYear()}
        </Footer>
      </Layout>
      {isLoading && <LoadingContainer loadingText={"Fetching"} />}
      {showSystemNoContainer && (
        <SystemNumberDialog
          setShowSystemNoContainer={setShowSystemNoContainer}
          showSystemNoContainer={showSystemNoContainer}
        />
      )}
      {showValidationContainer && (
        <ValidationContainer
          showValidationContainer={showValidationContainer}
          setShowValidationContainer={setShowValidationContainer}
          validateContainerData={validateContainerData}
          s3Path={s3Path}
          updatePartAanomoly={updatePartAanomoly}
        />
      )}
    </Layout>
  );
};
export default PartACorrection;
