import React, { useRef, useState } from "react";
import { useDropzone } from "react-dropzone";
import {
  Box,
  Typography,
  Button,
  Stack,
  Alert,
  CircularProgress,
  Modal,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from "@mui/material";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import FileDownloadIcon from "@mui/icons-material/FileDownload";
import DownloadIcon from "@mui/icons-material/Download";


type TableDefinition = {
  baseUrl: string;
};

export const BundleImport = ({ baseUrl }: TableDefinition) => {
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);

  const { getRootProps, getInputProps, isDragActive, open } = useDropzone({
    accept: {
      "application/vnd.ms-excel": [],
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [],
    },
    maxFiles: 1,  // 👈 Limit the number of files to 1
    onDrop: (acceptedFiles, rejectedFiles) => {
      if (rejectedFiles.length > 0) {
        setError("Invalid file format or too many files. Please upload a single Excel file (.xls or .xlsx)");
      } else {
        setError("");
        setLoading(true);
        const fileInput = document.getElementById("hidden-file-input") as HTMLInputElement;
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(acceptedFiles[0]);
        fileInput.files = dataTransfer.files;
  
        // Optional delay for UX
        setTimeout(() => {
          formRef.current?.submit();
          setLoading(false);
        }, 2000);
      }
    },
  });
  

  const handleImportClick = () => {
    open(); // Open file picker
  };

  // const previousImports = [
  //   {
  //     fileName: "import_qualification_01.xlsx",
  //     date: "2025-02-26 12:00 PM",
  //     failures: 3,
  //     action: "Download",
  //   },
  // ];

  return (
    <Box sx={{ textAlign: "center", padding: 3, maxWidth: 1000, mx: "auto" }}>
      <Stack direction="row" spacing={2} justifyContent="center" sx={{ mb: 2 }}>
        <Button
          variant="contained"
          sx={{
            color: "#067a40",
            background: "white",
            border: "2px solid #067a40",
            textTransform: "none", // Prevents all-caps
            "&:hover": { backgroundColor: "#056a35", color: "white" },
          }}
          startIcon={<CloudUploadIcon />}
          onClick={handleImportClick}
        >
          Import Bundle
        </Button>

        {/* 
        <Button
          variant="contained"
          sx={{
            backgroundColor: "#067a40",
            "&:hover": { backgroundColor: "#056a35" },
          }}
          startIcon={<FileDownloadIcon />}
        >
          Download Template Bundle
        </Button>
        */}
      </Stack>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {/* Hidden Form for File Upload */}
      <form
        ref={formRef}
        action={`${baseUrl}validation`}
        method="POST"
        encType="multipart/form-data"
      >
        <input
          {...getInputProps()}
          type="file"
          name="bundle"
          id="hidden-file-input"
          style={{ display: "none" }}
          multiple={false}  // 👈 Prevent multiple file selection in the native file picker
        />
      </form>

      {/* Dropzone */}
      <Box
        {...getRootProps()}
        sx={{
          border: "2px solid #645962",
          padding: "50px 0",
          textAlign: "center",
          cursor: "pointer",
          borderRadius: "8px",
          backgroundColor: isDragActive ? "#e5f5eb" : "#f9f9f9",
          "&:hover": { backgroundColor: "#e5f5eb" },
          transition: "background-color 0.3s",
          mb: 3,
        }}
      >
        <Typography
          variant="body1"
          sx={{ color: "#645962", fontWeight: "bold" }}
        >
          {isDragActive
            ? "Drop the files here..."
            : "Drag & drop files here or click to upload."}
        </Typography>
      </Box>

      {/* Loader Modal */}
      <Modal open={loading} sx={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Box
          sx={{
            backgroundColor: "white",
            padding: 3,
            borderRadius: 2,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: 2,
          }}
        >
          <CircularProgress color="success" />
          <Typography variant="body1">File uploaded successfully. Starting validation...</Typography>
        </Box>
      </Modal>

      {/* 
      <Typography variant="h5" component="h2" sx={{ fontWeight: "bold", textAlign: "left", mb: 1 }}>
        Previous Import
      </Typography>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell sx={{ fontWeight: "bold", color: "#067a40" }}>
                File Name
              </TableCell>
              <TableCell sx={{ fontWeight: "bold", color: "#067a40" }}>
                Date
              </TableCell>
              <TableCell sx={{ fontWeight: "bold", color: "#067a40" }}>
                Failures
              </TableCell>
              <TableCell sx={{ fontWeight: "bold", color: "#067a40" }}>
                Action
              </TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {previousImports.map((row, index) => (
              <TableRow key={index}>
                <TableCell>{row.fileName}</TableCell>
                <TableCell sx={{ textAlign: "center" }}>{row.date}</TableCell>
                <TableCell sx={{ textAlign: "center" }}>
                  {row.failures}
                </TableCell>
                <TableCell sx={{ textAlign: "center" }}>
                  <Button
                    variant="text"
                    sx={{
                      color: "#067a40",
                      "&:hover": { color: "#056a35" },
                    }}
                    endIcon={<DownloadIcon />}
                  >
                    {row.action}
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer> 
      */}
    </Box>
  );
};
