import React, { useEffect, useState } from "react";
import { Box, Button} from "@mui/material"
import { ToastContainer } from "react-toastify";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import HomeIcon from "@mui/icons-material/Home";
import LoadingContainer from "./LoadingContainer";
import SystemNumberDialog from "./SystemNumberDialog";

import { Breadcrumb, Layout, Menu, Typography, theme } from "antd";
import { useNavigate } from "react-router-dom";
import TableComponent from "./TableComponent";
import { useDispatch, useSelector } from "react-redux";
import TableComponentAdditionalSheet from "./TableComponentAdditionalSheet";
const { Header, Content, Footer, Sider } = Layout;

function AttendanceAdditionalSheet() {
    const [tableRowData, setTableRowData] = useState([]);
    
    const [windowWidth, setWindowWidth] = useState(window.innerWidth);
    const [collapsed, setCollapsed] = useState(false);
    const [anomolyData, setAnomolyData] = useState([]);
    const [filteredAnomolyData,setFilterAnomolyData] = useState([])
    const [isLoading, setIsLoading] = useState(false);
    const [distinctExamCentreCodes,setDistinctExamCentreCodes] = useState([])
    const dispatch = useDispatch()
    const reduxAnomolyData = useSelector((state) => state.attendenceAnomolyData);
    const [showSystemNoContainer, setShowSystemNoContainer] = useState(false);
    const [filterSelectedExamCentreCode,setFilterSelectedExamCentreCode] = useState("")
    const reduxSystemNo = useSelector((state) => state?.systemNumber);
    
    useEffect(() => {
      if (!reduxSystemNo) {
        setShowSystemNoContainer(true);
      } else {
        
        fetchAnomalyData(reduxSystemNo)
        
      }
    },[])
    
    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]);


    function createData(
        image_name,
        s3_image_path
      ) {
        return {
          image_name,
          s3_image_path
        };
      }
      

    // useEffect(()=>{
    //     const tmpData = [];
    //     for (const data of anomolyData) {
    //       tmpData.push(
    //         createData(
    //             data.image_name,
    //             data.s3_image_path
    //         //   data.attendence_serial_no,
    //         //   data.answer_booklet_sno,
    //         //   data.exam_centre_code,
    //         //   data.exam_centre,
    //         //   data.student_name,
    //         //   data.register_number,
    //         //   data.reassigned_serial_no
    //         )
    //       );
    //     }
    //     console.log("Tmp data is : ", tmpData);
    //     if (tmpData.length > 0) {
    //       setTableRowData(tmpData);
    //     }
    //   },[anomolyData])

      const updateSystemReservationStatus = async (systemRecords) => {
        const payload = {
          systemRecords,
          sysNo:reduxSystemNo
        };
        try {
          fetch(
            `${
              import.meta.env.VITE_REACT_APP_BACKEND_URL
            }/updateSystemReservationStatusAttendence`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify(payload),
            }
          )
            .then((response) => response.json())
            .then((responseData) => {
              console.log("response from updation : ", responseData);
            });
        } catch (error) {
          throw new Error("Error in update system records : ", systemRecords);
        }
      };

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

      const fetchAnomalyData = (reduxSystemNo) => {
        console.log("Fetching.......");
        setIsLoading(true);
        fetch(
          `${
            import.meta.env.VITE_REACT_APP_BACKEND_URL
          }/fetchAnamolyAttendenceAdditionalSheetData?sysNo=${reduxSystemNo}`,
          {
            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("System record ====== ",responseData.systemRecord)
              var systemRecords = responseData?.data
              if(!responseData.systemRecord){
                systemRecords = getRecordsBySystemId(
                  responseData?.data,
                  reduxSystemNo
                );
              }
              updateSystemReservationStatus(systemRecords);
              console.log("System records : ", systemRecords);
              // if (searchParamsType === "old") {
              //   localStorage.setItem(
              //     "part-a-old-anomoly",
              //     JSON.stringify(systemRecords)
              //   );
              // } else if (searchParamsType !== "old") {
              //   localStorage.setItem(
              //     "part-a-anomoly",
              //     JSON.stringify(systemRecords)
              //   );
              // }
              setAnomolyData(systemRecords);
              // dispatch(updatePartAanomolyData(systemRecords));
              const tmpData = [];
              for (const data of systemRecords) {
                tmpData.push(
                  createData(
                      data.image_name,
                      data.s3_image_path
                  //   data.attendence_serial_no,
                  //   data.answer_booklet_sno,
                  //   data.exam_centre_code,
                  //   data.exam_centre,
                  //   data.student_name,
                  //   data.register_number,
                  //   data.reassigned_serial_no
                  )
                );
              }
              // console.log("Tmp data is : ", tmpData);
              if (tmpData.length > 0) {
                setTableRowData(tmpData);
              }
              
            }
          })
          .catch((error) => {
            console.error("Error fetching data: ", error);
            setIsLoading(false);
          });
      };


      // useEffect(() => {
      //   if (reduxAnomolyData.length > 0) {
      //     console.log("Redux anomoly data found")
      //     setAnomolyData(reduxAnomolyData)
      //   } else {
      //     console.log("Redux anomoly data not found")
      //     fetchAnomalyData();
      //   }
      // }, []);
    
    
      useEffect(()=>{
       const tmpData = []
       for(var data in anomolyData){
        if(data?.exam_centre_code == filterSelectedExamCentreCode){
          tmpData.push(data)
        }
       }
    
      },[filterSelectedExamCentreCode])

      const handleSystemNoChange = () => {
        console.log("System No Change is called");
        setShowSystemNoContainer(true);
      };
    
      useEffect(() => {
        console.log("System no container show status : ", showSystemNoContainer);
      }, [showSystemNoContainer]);

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

  const navigate = useNavigate()

  return (
    <Layout
      style={{
        minHeight: "100vh",
      }}
    >
      <ToastContainer />
      <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">
              {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>
                  )}
              <Button
                className="bg-primary p-1 text-light"
                onClick={() => {
                  navigate("/");
                }}
              >
                <HomeIcon />
              </Button>
            </Box>
          </Box>
        </Header>

        <Content
            style={{
                margin: "16px 16px",
            }}
        >
            <Box className="w-100 d-flex justify-content-between">
                <Box className="w-100 d-flex justify-content-center">
                {tableRowData.length > 0 && (
                    <TableComponent
                    filterSelectedExamCentreCode = {filterSelectedExamCentreCode}
                    setFilterSelectedExamCentreCode = {setFilterSelectedExamCentreCode}
                    rows={tableRowData}
                    type={"AdditionalSheet"}
                    distinctExamCentreCodes = {distinctExamCentreCodes}
                    />
                )}
                    {tableRowData.length == 0 && (
                    <Box className="w-100 d-flex justify-content-center py-2 align-items-center text-center">
                    <h6>No Data Found !!</h6>
                    </Box>
                )}
                </Box>
          </Box>
        </Content>


      </Layout>
      {isLoading && <LoadingContainer loadingText={"Loading"} />}
      {showSystemNoContainer && (
        <SystemNumberDialog
          setShowSystemNoContainer={setShowSystemNoContainer}
          showSystemNoContainer={showSystemNoContainer}
        />
      )}
    </Layout>
  );
}

export default AttendanceAdditionalSheet;
