import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { Box, Button, Typography } from "@mui/material";
import AntdesignLayout from "./AntdesignLayout";
import LoadingContainer from "./LoadingContainer";
import infinity_loader from "../../assets/Infinity_loader.gif";
import Notification from "./Notification"; // Import the Notification component
import { Height } from "@mui/icons-material";
import ZoomInIcon from "@mui/icons-material/ZoomIn";
import ZoomOutIcon from "@mui/icons-material/ZoomOut";
import DeleteIcon from "@mui/icons-material/Delete";
import { Navigate} from "react-router-dom";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
} from "@mui/material";

const UploadMarksheetDataContainer = () => {
  const uploadDataStyleContainer = {
    backgroundColor: "white",
    borderRadius: "10px",
    minWidth: "800px",
    padding: "25px 40px",
    margin: "10px",
  };

  const [selectedFile, setSelectedFile] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [notification, setNotification] = useState(null); // Notification state
  const [processList, setProcesList] = useState([]);

  const showNotification = (message, type) => {
    setNotification({ message, type });
  };

  const handleFileChange = (event) => {
    const file = event.target.files && event.target.files[0];
    setSelectedFile(file);
  };

  useEffect(() => {
    fetchCertificateDataInsertionList();
    const fetchInterval = setInterval(() => {
      fetchCertificateDataInsertionList();
    }, 2000);

    return () => {
      clearInterval(fetchInterval);
    };
  }, []);

  const fetchCertificateDataInsertionList = async () => {
    try {
      const response = await fetch(
        `${
          import.meta.env.VITE_REACT_APP_BACKEND_URL
        }/fetchCertificateDataInsertionList`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      const responseData = await response.json();
      console.log("Response ==== ", responseData);
      if (responseData?.status == "success") {
        setProcesList(responseData?.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleUploadClick = async () => {
    // Logic to handle file upload (send the file to server, etc.)
    if (selectedFile) {
      setIsLoading(true);
      console.log(`File selected: ${selectedFile.name}`);
      try {
        const formData = new FormData();
        formData.append("file", selectedFile);
        const response = await fetch(
          `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/uploadCertificateData`,
          {
            method: "POST",
            body: formData,
          }
        );

        const result = await response.json();
        setIsLoading(false);
        if (response.ok) {
          console.log(`File uploaded successfully: ${result.message}`);
          showNotification("File Uploaded Successfully ...", "success");
        } else {
          console.error(`Error during upload: ${result.message}`);
          showNotification("Something Went Wrong ...", "error");
        }
      } catch (error) {
        setIsLoading(false);
        showNotification("Something Went Wrong ...", "error");
        console.error("Error uploading the file:", error);
      }
    }
  };

  const handleSampleDownload = async () => {
    console.log("Downloading ....");
    try {
      const response = await fetch(
        `${
          import.meta.env.VITE_REACT_APP_BACKEND_URL
        }/download/certificate/sample`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "sample_certificate_upload_data.csv"; // Customize the file name here
      document.body.appendChild(a);
      a.click();
      a.remove(); // Cleanup
    } catch (error) {
      console.error("Error downloading the file:", error);
    }
  };

  const parseCreatedOn = (dateValue) => {
    console.log("parse created on ....", typeof dateValue);
    if (!dateValue) {
      return null; // Handle invalid input
    } else if (typeof dateValue == "number") {
      dateValue = String(dateValue);
    }

    const year = parseInt(dateValue.substring(0, 4), 10);
    console.log("year ===== ", year);
    const month = parseInt(dateValue.substring(4, 6), 10) - 1; // Month is 0-based in JS
    const day = parseInt(dateValue.substring(6, 8), 10);
    const hours = parseInt(dateValue.substring(8, 10), 10);
    const minutes = parseInt(dateValue.substring(10, 12), 10);
    const seconds = parseInt(dateValue.substring(12, 14), 10);

    const parsedDate = new Date(year, month, day, hours, minutes, seconds);

    // Check if the date is valid
    if (isNaN(parsedDate.getTime())) {
      return null; // Invalid date
    }

    return parsedDate;
  };

  return (
    <AntdesignLayout>
      <Box className="d-flex justify-content-center">
        <Box style={uploadDataStyleContainer}>
          <input
            accept=".csv" // File types to accept
            style={{ display: "none" }}
            id="contained-button-file"
            type="file"
            onChange={handleFileChange}
          />
          <Box className="py-3" style={{ fontSize: "18px" }}>
            <strong>Certificate Generation Data Upload:</strong>
          </Box>
          <Box style={{ fontSize: "15px" }}>
            <strong>Note :</strong> The upload data has to be a CSV format with
            the following sample CSV header structure.Please Make sure before
            Uploading the Data ..
          </Box>
          <Box className="d-flex justify-content-center align-items-center gap-2 py-4">
            <label htmlFor="contained-button-file">
              <Button variant="contained" color="primary" component="span">
                Choose File
              </Button>
            </label>
            <label>
              <Button
                variant="contained"
                color="primary"
                component="span"
                onClick={handleSampleDownload}
              >
                Download Sample CSV
              </Button>
            </label>
          </Box>
          {selectedFile && (
            <Box
              className="d-flex justify-content-center gap-2 rounded p-2 w-100"
              style={{ backgroundColor: "#e4f7f5" }}
            >
              <Typography variant="body1" sx={{ mt: 2 }}>
                <strong>Selected File :</strong> {selectedFile.name}
              </Typography>
              <DeleteIcon
                style={{ cursor: "pointer" }}
                onClick={() => setSelectedFile(null)}
              />
            </Box>
          )}

          {selectedFile && (
            <Button
              variant="contained"
              color="secondary"
              onClick={handleUploadClick}
              sx={{ mt: 2 }}
              disabled={!selectedFile}
            >
              Upload File
            </Button>
          )}
          <Box>
            <Link to="/certificate/gen">
              <Button
                variant="contained"
                color="secondary"
                sx={{ mt: 2 }}
              >
                Generate For Individual
              </Button>
            </Link>
          </Box>
        </Box>
      </Box>
      <Box
        className="py-3"
        style={{ width: "70%", margin: "auto", textAlign: "center" }}
      >
        {processList.length > 0 && (
          <>
            <TableContainer component={Paper}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>
                      <strong>ID</strong>
                    </TableCell>
                    <TableCell>
                      <strong>File Name</strong>
                    </TableCell>
                    <TableCell>
                      <strong>Status</strong>
                    </TableCell>
                    <TableCell>
                      <strong>Created on</strong>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {processList.map((processData) => (
                    <TableRow key={processData.id}>
                      <TableCell>
                        {processData?.job_vidh_ms_solutions_id}
                      </TableCell>
                      <TableCell>{processData?.file_name}</TableCell>
                      <TableCell style={{ textAlign: "center" }}>
                        <button
                          style={{
                            backgroundColor:
                              processData?.status_code === "JQ"
                                ? "red"
                                : "green",
                            color: "white",
                            borderRadius: "10px",
                            padding: "3px 10px",
                          }}
                        >
                          {processData?.status_code}
                        </button>
                      </TableCell>
                      <TableCell>
                        {processData?.created_on
                          ? new Intl.DateTimeFormat("en-US", {
                              year: "numeric",
                              month: "long",
                              day: "numeric",
                              hour: "2-digit",
                              minute: "2-digit",
                              second: "2-digit",
                            }).format(parseCreatedOn(processData?.created_on))
                          : "N/A"}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </>
        )}
      </Box>
      {isLoading && <LoadingContainer />}
      {notification && (
        <Notification
          message={notification.message}
          type={notification.type}
          onClose={() => setNotification(null)}
        />
      )}
    </AntdesignLayout>
  );
};

export default UploadMarksheetDataContainer;
