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 BarcodeInput from "./BarcodeInput";
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';


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 [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 navigate = useNavigate()
  let [searchParams, setSearchParams] = useSearchParams();
  const searchParamsBarcode = searchParams.get("barcode");
  console.log("Serach parmas sno : ", searchParamsBarcode);
  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 (searchParamsBarcode) {
      setBookletInput(searchParamsBarcode);
    }
  }, [searchParamsBarcode]);

  useEffect(() => {
    submitBookletInput();
  }, [bookletInput]);



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

  const submitBookletInput = async () => {
    setIsLoading(true);
    setStudentData(null);
    if (!bookletInput) {
      console.log("Returning");
      return;
    }
    const payload = {
      bookletInput,
    };
    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 updateReassignedSno = async () => {
    const payload = {
      bookletInput,
      reasssingedSno,
    };
    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();
    if (responseData.status === "success" && responseData?.status_code == 200) {
      console.log("Updation success");
      toast.success("Record Updated Successfully !!");
    } else if (
      responseData.status === "success" &&
      responseData?.status_code == 405
    ) {
      console.log("Updation not allowed");
      toast.error("Reassigned Serial No is Invalid !!");
    }
  };

  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">
                <BarcodeInput
                  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>
              )}
              {dataFetched && studentData && (
                <>
                  <Box>
                    <Box className="d-flex justify-content-start px-2 py-3">
                      <h6>Barcode Info:</h6>
                    </Box>

                    <Box className="px-2">
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="student-name-input">Register Number:</label>
                        <TextField
                          id="student-name-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.register_number}
                        />
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-code-input">
                          Subject Code:
                        </label>
                        <TextField
                          id="exam-centre-code-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.subject_code}
                        />
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-input">Type:</label>
                        <TextField
                          id="exam-centre-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.type}
                        />
                      </Box>
                      {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-date-input">Exam Date:</label>
                        <TextField
                          id="exam-date-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.ref_exam_date}
                        />
                      </Box> */}
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="reassigned-serial-no-input">
                          Reassigned Serial No:
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="reassigned-serial-no-input"
                            disabled={!updateReassigned}
                            className="w-100"
                            value={studentData.reassigned_serial_no}
                            autoComplete="off"
                            onChange={(e) => {
                              setReassignedSno(e.target.value);
                            }}
                          />
                          <Button
                            onClick={() => {
                              setUpdateReassigned(!updateReassigned);
                            }}
                          >
                            <EditButton />
                          </Button>
                        </Box>
                      </Box>
                      <Box className="py-2 d-flex justify-content-start">
                        <Button
                          className="text-light bg-primary p-3"
                          disabled={!updateReassigned}
                          onClick={updateReassignedSno}
                        >
                          Update
                        </Button>
                      </Box>
                    </Box>
                  </Box>
                </>
              )}
            </Box>
            <Box className="w-md-25 d-flex d-md-none flex-column">
              <Box className="d-flex justify-content-between">
                <BarcodeInput
                  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>
              )}
              {dataFetched && studentData && (
                <>
                  <Box>
                    <Box className="d-flex justify-content-start px-2 py-3">
                      <h6>Barcode Info:</h6>
                    </Box>

                    <Box className="px-2">
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="student-name-input">Register Number:</label>
                        <TextField
                          id="student-name-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.register_number}
                        />
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-code-input">
                          Subject Code:
                        </label>
                        <TextField
                          id="exam-centre-code-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.subject_code}
                        />
                      </Box>
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-centre-input">Type:</label>
                        <TextField
                          id="exam-centre-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.type}
                        />
                      </Box>
                      {/* <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="exam-date-input">Exam Date:</label>
                        <TextField
                          id="exam-date-input"
                          disabled="true"
                          className="w-100"
                          value={studentData.ref_exam_date}
                        />
                      </Box> */}
                      <Box className="d-flex flex-column align-items-start gap-2 py-2">
                        <label for="reassigned-serial-no-input">
                          Reassigned Serial No:
                        </label>
                        <Box className="d-flex justify-content-between w-100">
                          <TextField
                            id="reassigned-serial-no-input"
                            disabled={!updateReassigned}
                            className="w-100"
                            value={studentData.reassigned_serial_no}
                            autoComplete="off"
                            onChange={(e) => {
                              setReassignedSno(e.target.value);
                            }}
                          />
                          <Button
                            onClick={() => {
                              setUpdateReassigned(!updateReassigned);
                            }}
                          >
                            <EditButton />
                          </Button>
                        </Box>
                      </Box>
                      <Box className="py-2 d-flex justify-content-start">
                        <Button
                          className="text-light bg-primary p-3"
                          disabled={!updateReassigned}
                          onClick={updateReassignedSno}
                        >
                          Update
                        </Button>
                      </Box>
                    </Box>
                  </Box>
                </>
              )}
            </Box>
            <Box className="w-75 d-none d-md-block">
              {dataFetched && studentData && (
                <img
                  src={`https://docs.exampaper.vidh.ai/${studentData.s3_path}`}
                  width="60%"
                  height="auto"
                />
              )}
            </Box>
            <Box className="w-md-75 d-block d-md-none">
              {dataFetched && studentData && (
                <img
                  src={`https://docs.exampaper.vidh.ai/${studentData.s3_path}`}
                  width="60%"
                  height="auto"
                />
              )}
            </Box>
          </Box>
        </Content>
        <Footer
          style={{
            textAlign: "center",
          }}
        >
          exampaper.vidh.ai ©{new Date().getFullYear()}
        </Footer>
      </Layout>
      {isLoading && <LoadingContainer loadingText={"Fetching"} />}
    </Layout>
  );
};
export default PartACorrection;
