import { Layout, theme } from "antd";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom/dist";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import HomeIcon from "@mui/icons-material/Home";
import { useDispatch, useSelector } from "react-redux";
import { Box, Button, Card, CardContent, Typography, CircularProgress } from "@mui/material";
import { updateEvQrcodeList } from "../redux/actions/actions";
import SystemNumberDialog from "./SystemNumberDialog";
import { toast, ToastContainer } from "react-toastify";

const { Content, Header } = Layout;

function EvQrcode() {
  const [isLoading, setIsLoading] = useState(false);
  const [showSystemNoContainer, setShowSystemNoContainer] = useState(false);
  const [anomalyData, setAnomalyData] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);

  const navigate = useNavigate();

  const evQrcodeList = useSelector((state) => state?.evQrcodeList);
  console.log("evQrcodeList = ", evQrcodeList);

  const reduxSystemNo = useSelector((state) => state?.systemNumber);
  console.log("systemno: ", reduxSystemNo);

  const dispatch = useDispatch();
  const { token: { colorBgContainer } } = theme.useToken();

  useEffect(() => {
    if (!reduxSystemNo) {
      setShowSystemNoContainer(true);
    } else {
      if (evQrcodeList.length > 0) {
        setAnomalyData(evQrcodeList);
      } else {
        fetchAnomalyData();
      }
    }
  }, [reduxSystemNo]);

  useEffect(() => {
    if (evQrcodeList.length > 0) {
      setAnomalyData(evQrcodeList);
    }
  }, [evQrcodeList]);

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

  const updateSystemReservationStatus = async (systemRecords) => {
    const payload = {
      systemRecords,
      sysNo: reduxSystemNo,
    };
    try {
      fetch(
        `${
          import.meta.env.VITE_REACT_APP_BACKEND_URL
        }/updateSystemReservationStatusEvQrcode`,
        {
          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);
    }
  };

  const fetchAnomalyData = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`${import.meta.env.VITE_REACT_APP_BACKEND_URL}/getEvRecords`, {
        method: "POST",
        body: JSON.stringify({
            sysno: reduxSystemNo
        }),
        headers: {
          "Content-Type": "application/json",
        },
      });
      const responseData = await response.json();
      var systemRecords = responseData?.data;
      console.log("System record ====== ", responseData.systemRecord);
      if (!responseData.systemRecord) {
        systemRecords = getRecordsBySystemId(responseData?.data, reduxSystemNo);
      }
      console.log("System records : ", systemRecords);

      dispatch(updateEvQrcodeList(systemRecords));
      updateSystemReservationStatus(systemRecords);
    } catch (error) {
      console.error("Error fetching data: ", error);
    } finally {
      setIsLoading(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;
  }

  const handleNext = () => {
    const newItems = anomalyData.filter((_, index) => index !== currentIndex);
    setAnomalyData(newItems);
    if (currentIndex >= newItems.length) {
      setCurrentIndex(0);
    }
  };

  const handleUpdate = async() => {
    try {
        const inputValue = document.getElementById('qrcodeInput').value;
        console.log("inputvalu = ", inputValue)

        const payload = {
            imageName: currentItem.image_name,
            qrvalue: inputValue,
        };
        console.log("payload=", payload)

        const response = await fetch(`${import.meta.env.VITE_REACT_APP_BACKEND_URL}/updateEvRecord`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body:JSON.stringify(payload)
        });
        const responseData = await response.json();
        console.log("responsedata: ", responseData)
        if (responseData?.status_code === 200) {
            toast.success("Record Updated Successfully");
            handleNext()
            document.getElementById('qrcodeInput').value = ''
        }else{
            toast.error("Updation Failed");
        }

      } catch (error) {
        console.error("Error fetching data: ", error);
      } finally {
        setIsLoading(false);
      }
  }

  const handleArrowBack = () => {
    dispatch(updateEvQrcodeList([]));
    navigate(-1)
  }

  if (isLoading) {
    return <CircularProgress />;
  }

  const currentItem = anomalyData[currentIndex];
  const imageUrl = currentItem ? `https://docs.exampaper.vidh.ai/${currentItem.s3_path}` : '';

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Layout>
        <ToastContainer />
        <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={handleArrowBack}>
              <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>
          {currentItem ? (
            <Box className="d-flex justify-content-center align-items-center flex-column" style={{ minHeight: '80vh' }}>
              <Card style={{ display: 'flex', flexDirection: 'row', margin:'20px 20px 20px 20px' }}>
                <Box style={{ flex: '20%', padding: '20px', marginTop:'30px', textAlign:'left' }}>
                    <Typography variant="h5" style={{paddingBottom:'20px'}}>Records Count: {anomalyData.length}</Typography>
                  <Typography variant="h6">Image Name: {currentItem.image_name}</Typography>
                  {/* <Typography variant="body2">S3 Path: {currentItem.s3_path}</Typography> */}
                  <Typography variant="subtitle1" style={{paddingTop:'20px', fontWeight:'bold'}}>Qrcode Value</Typography>
                  <input
                    type="text"
                    id="qrcodeInput"
                    placeholder="Enter qrcode value"
                    style={{
                        marginTop: '10px',
                        width: '100%',
                        padding: '5px',
                        backgroundColor: 'transparent',
                        color: '#000000' // black text color
                    }}
                    />
                  <Box mt={2}>
                    <Button variant="contained" color="primary" onClick={handleNext} style={{ marginRight: 10 }}>
                      Skip
                    </Button>
                    <Button variant="contained" color="secondary" onClick={handleUpdate} style={{backgroundColor:'green'}}>
                      Update
                    </Button>
                  </Box>
                </Box>
                <CardContent style={{ flex: '80%' }}>
                  <img src={imageUrl} alt={currentItem.image_name} style={{ width: '100%', marginTop: '20px' }} />
                </CardContent>
              </Card>
            </Box>
          ) : (
            <Typography>No items to display</Typography>
          )}
        </Content>

        {showSystemNoContainer && (
          <SystemNumberDialog setShowSystemNoContainer={setShowSystemNoContainer} showSystemNoContainer={showSystemNoContainer} />
        )}
      </Layout>
    </Layout>
  );
}

export default EvQrcode;
