import React, { useState } from "react";
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Breadcrumb, Layout, Menu, Typography, theme } from "antd";
import BookletInput from "./BookletInput";
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 { useDispatch, useSelector } from "react-redux";
import { updateAttendenceAnomolyData } from "../redux/actions/actions";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";

const { Header, Content, Footer, Sider } = Layout;
function getItem(label, key, icon, children) {
  return {
    key,
    icon,
    children,
    label,
  };
}

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

const AttendenceAdditionalRecordCorrection = () => {
  console.log("Checking1 ...");
  const [collapsed, setCollapsed] = useState(false);
  const [bookletInput, setBookletInput] = 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 [registerNumber, setRegisterNumber] = useState(null);
  const [backgroundPosition, setBackgroundPosition] = useState("0% 0%");
  const [zoomed, setZoomed] = useState(false);
  const dispatch = useDispatch();
  const [scaleWidthValue, setScaleWidthValue] = useState(80);
  const [rotateValue, setRotateValue] = useState(0);
  const [attendenceQRcode,setAttendenceQRcode] = useState(null)

  // const reduxAnomolyData = useSelector((state) => state.attendenceAnomolyData);
  // console.log("Anomoly Data is : ", reduxAnomolyData);
  const [anomolyData, setAnomolyData] = useState([]);

  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);
  };

  const navigate = useNavigate();
  let [searchParams, setSearchParams] = useSearchParams();
  const searchParamsqrcode = searchParams.get("qrcode");
  // console.log("Serach parmas sno : ", searchParamsBookletSerialNo);
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  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 (searchParamsqrcode) {
      setAttendenceQRcode(searchParamsqrcode);
    }
  }, [searchParamsqrcode]);

  useEffect(() => {
    submitQrInputData();
  }, [attendenceQRcode]);

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

  // useEffect(() => {
  //   if (reduxAnomolyData.length === 0) {
  //     fetchAnomalyData();
  //   }
  // }, []);

  const fetchAnomalyData = () => {
    console.log("Fetching.......");
    setIsLoading(true);
    fetch(
      `${
        import.meta.env.VITE_REACT_APP_BACKEND_URL
      }/fetchAnamolyAttendenceData`,
      {
        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") {
          setAnomolyData(responseData?.data);
          console.log("Data to be stored in store : ", responseData?.data);
          // dispatch(updateAttendenceAnomolyData(responseData?.data));
        }
      })
      .catch((error) => {
        console.error("Error fetching data: ", error);
        setIsLoading(false);
      });
  };

  const submitQrInputData = async () => {
    setIsLoading(true);
    setStudentData(null);
    if (!bookletInput) {
      console.log("Returning");
    }
    const payload = {
      attendenceQRcode,
    };
    const response = await fetch(
      `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/fetchAttendenceAdditionalqrData`,
      {
        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) {
        setStudentData(responseData.data[0]);
        const student_data = responseData.data[0];
        setRegisterNumber(student_data?.register_number);
      }
    }
  };

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

  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 ImageStyle = {
    // transform: `scale(${scaleValue})`,
    transformOrigin: "left", // Adjust the zoom origin as needed
    transition: "transform 0.2s ease-in-out",
  };

  const containerStyle = {
    width: "auto", // Set the width and height as needed
    maxHeight: "90%",
    overflowX: "scroll",
    position: "relative",
  };

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

  const updateReassignedSno = async () => {
    setIsLoading(true);
    // if(reduxAnomolyData.length === 0){
    //   console.log("Redux anomoly data length is 0.......")
    //   fetchAnomalyData()
    // }
    console.log("Reassgined Sno : ", reasssingedSno);
    const payload = {
      bookletInput,
      reasssingedSno,
      registerNumber,
    };
    const response = await fetch(
      `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/updateReassingedSno`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      }
    );
    const responseData = await response.json();
    setIsLoading(false);
    setReassignedSno(null);
    if (responseData.status === "success" && responseData?.status_code == 200) {
      console.log("Updation success");
      toast.success("Record Updated Successfully !!");
      var index = 0
      var RecordIndex = 0
      const filteredData = reduxAnomolyData.filter((data) => {
        if (data?.student_slno === searchParamsBookletSerialNo) {
          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("Filtered Data: ", filteredData);
      // dispatch(updateAttendenceAnomolyData(filteredData));
      if (filteredData.length > 0) {
        navigate(
          `/anomoly/reassigned/booklet?sno=${filteredData[RecordIndex].student_slno}`
        );
      }
    } else if (
      responseData.status === "success" &&
      responseData?.status_code == 405
    ) {
      console.log("Updation not allowed");
      toast.error("Reassigned Serial No is Invalid !!");
    }
  };

  const markAsAssigned = async () => {
    setIsLoading(true);
    const payload = { bookletInput };
    const response = await fetch(
      `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/markAsAssigned`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      }
    );
    const responseData = await response.json();
    setIsLoading(false);
    if (responseData.status === "success") {
      toast.success("Record Updated Successfully !!");
      var index = 0
      var RecordIndex = 0
      const filteredData = reduxAnomolyData.filter((data) => {
        if (data?.student_slno === searchParamsBookletSerialNo) {
          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("Filtered Data: ", filteredData);
      // dispatch(updateAttendenceAnomolyData(filteredData));
      if (filteredData.length > 0) {
        navigate(
          `/anomoly/reassigned/booklet?sno=${filteredData[RecordIndex].student_slno}`
        );
      }
    }
  };

  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,
          }}
        >
          <Box className="d-flex justify-content-between h-100 py-1 px-2">
            <Button
              className="bg-primary p-1 text-light"
              onClick={() => {
                navigate(-1);
              }}
            >
              <ArrowBackIcon />
            </Button>
            <Box className="d-flex justify-content-between gap-2">
              <Button
                className="bg-primary p-1 text-light"
                onClick={() => {
                  navigate("/anomoly/reassigned/stats");
                }}
              >
                <QueryStatsIcon />
              </Button>
              <Button
                className="bg-primary p-1 text-light"
                onClick={() => {
                  navigate("/");
                }}
              >
                <HomeIcon />
              </Button>
            </Box>
          </Box>
          {/* <Box>Reassigned Booklet Serial Manual Updation :</Box> */}
        </Header>
        <Content
          style={{
            margin: "16px 16px",
          }}
        >
          {/* <Breadcrumb
            style={{
              margin: "16px 0",
            }}
          >
            <Breadcrumb.Item>User</Breadcrumb.Item>
            <Breadcrumb.Item>Bill</Breadcrumb.Item>
          </Breadcrumb> */}
          {/* <div
            style={{
              padding: 24,
              minHeight: 360,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            Bill is a cat.
          </div> */}
          <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-between">
                {/* <BookletInput
                  className="d-flex flex-1"
                  setBookletInput={setBookletInput}
                  bookletInput={bookletInput}
                  setDataFetched={setDataFetched}
                /> */}

                {/* <Button
                  className="px-md-5 px-2 mx-1 mx-md-2 text-light bg-primary"
                  onClick={submitBookletInput}
                >
                  Submit
                </Button> */}
              </Box>
              {/* {!isLoading && !studentData && (
                <Box className="w-100 py-5">
                  <h6>Invalid Booklet Serial No !!</h6>
                </Box>
              )} */}
              {studentData && (
                <>
                  <Box>
                    <Box className="d-flex justify-content-start px-2 py-3">
                      <h6>
                        <u>Booklet Info:</u>
                      </h6>
                    </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>Booklet Serial No:</u>
                        </label>
                        <h5>{bookletInput}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="student-name-input" className="h6">
                          <u>Student Name:</u>
                        </label>
                        <h5>{studentData?.student_name}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-code-input" className="h6">
                          <u>Exam Center Code:</u>
                        </label>
                        <h5>{studentData?.exam_centre_code}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-input" className="h6">
                          <u>Exam Centre:</u>
                        </label>
                        <h5>{studentData.exam_centre}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-date-input" className="h6">
                          <u>Exam Date:</u>
                        </label>
                        <h5>{studentData?.exam_date}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="reassigned-serial-no-input">
                          <u>Reassigned Serial No:</u>
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="reassigned-serial-no-input"
                            className="w-100"
                            value={studentData.reassigned_serial_no}
                            placeholder={`Please enter the SNo.${studentData?.rownumber} Answer Booklet No`}
                            autoComplete="off"
                            onChange={(e) => {
                              setReassignedSno(e.target.value);
                            }}
                          />
                        </Box>
                      </Box>
                      <Box className="py-2 d-flex justify-content-start flex-column gap-2">
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          disabled={!reasssingedSno}
                          onClick={updateReassignedSno}
                        >
                          Update
                        </Button>
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          onClick={markAsAssigned}
                        >
                          Mark As Assigned
                        </Button>
                      </Box>
                    </Box>
                  </Box>
                </>
              )}
            </Box>
            <Box className="w-md-25 d-flex d-md-none flex-column">
              {/* {!isLoading && !studentData && (
                <Box className="w-100 py-5">
                  <h6>Invalid Booklet Serial No !!</h6>
                </Box>
              )} */}
              {studentData && (
                <>
                  <Box>
                    <Box className="d-flex justify-content-start px-2 py-3">
                      <h6>
                        <u>Booklet Info:</u>
                      </h6>
                    </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>Booklet Serial No:</u>
                        </label>
                        <h5>{bookletInput}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="student-name-input" className="h6">
                          <u>Student Name:</u>
                        </label>
                        <h5>{studentData?.student_name}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-code-input" className="h6">
                          <u>Exam Center Code:</u>
                        </label>
                        <h5>{studentData?.exam_centre_code}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-input" className="h6">
                          <u>Exam Centre:</u>
                        </label>
                        <h5>{studentData.exam_centre}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-date-input" className="h6">
                          <u>Exam Date:</u>
                        </label>
                        <h5>{studentData?.exam_date}</h5>
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="reassigned-serial-no-input">
                          <u>Reassigned Serial No:</u>
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="reassigned-serial-no-input"
                            className="w-100"
                            value={studentData.reassigned_serial_no}
                            placeholder={`Please enter the SNo.${studentData?.rownumber} Answer Booklet No`}
                            autoComplete="off"
                            onChange={(e) => {
                              setReassignedSno(e.target.value);
                            }}
                          />
                        </Box>
                      </Box>
                      <Box className="py-2 d-flex justify-content-start flex-column gap-2">
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          disabled={!reasssingedSno}
                          onClick={updateReassignedSno}
                        >
                          Update
                        </Button>
                        <Button
                          className="text-light bg-primary p-3 w-100"
                          onClick={markAsAssigned}
                        >
                          Mark As Assigned
                        </Button>
                      </Box>
                    </Box>
                  </Box>
                </>
              )}
            </Box>
            <Box
              className="w-75 d-none d-md-block"
              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>
                  <img
                    className="scanned-img"
                    src={`https://docs.exampaper.vidh.ai/${studentData?.s3_image_path}`}
                    width={`${scaleWidthValue}%`}
                  />
                </>
              )}
            </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>
                  <img
                    className="scanned-img"
                    src={`https://docs.exampaper.vidh.ai/${studentData.s3_path}`}
                    width={`${scaleWidthValue}%`}
                  />
                </>
              )}
            </Box>
          </Box>
        </Content>
        <Footer
          style={{
            textAlign: "center",
          }}
        >
          exampaper.vidh.ai ©{new Date().getFullYear()}
        </Footer>
      </Layout>
      {isLoading && <LoadingContainer loadingText={"Fetching"} />}
    </Layout>
  );
};
export default AttendenceAdditionalRecordCorrection;
