import React, { useState } from "react";
import { Box, Button, Dialog, TextField, CircularProgress } from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import { useMutation, useQueryClient } from "@tanstack/react-query";

const FILE_EXTENSION = ".schem";

export default function NewStructure() {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [file, setFile] = useState(null);

  const queryClient = useQueryClient();

  const uploadStructureMutation = useMutation({
    mutationFn: async ({ name, description, file }) => {
      const formData = new FormData();
      formData.append("name", name);
      formData.append("description", description);
      formData.append("structureFile", file);

      const res = await fetch("/api/structures", {
        method: "POST",
        body: formData,
      });
      if (!res.ok) throw new Error(await res.text());
      return res.json();
    },
    onSuccess: (created) => {
      queryClient.setQueryData(["structures"], (old = []) => [...old, created]);
      setName("");
      setDescription("");
      setFile(null);
      setOpen(false);
      alert("Structure uploaded successfully!");
    },
    onError: (err) => {
      console.error("createStructure failed", err);
      alert("Structure could not be created – check the console for details.");
    },
  });

  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];
    if (selectedFile && !selectedFile.name.endsWith(FILE_EXTENSION)) {
      alert(`Invalid file type. Please upload a file with the ${FILE_EXTENSION} extension.`);
      event.target.value = "";
      setFile(null);
    } else {
      setFile(selectedFile);
    }
  };

  const handleUpload = () => {
    if (!file) {
      alert("Please select a valid .schem file.");
      return;
    }
    if (!name || !description) {
      alert("Please fill in all fields.");
      return;
    }
    uploadStructureMutation.mutate({ name, description, file });
  };

  return (
    <>
      {/* Trigger button */}
      <Box sx={{ mt: 4, display: "flex", justifyContent: "flex-end" }}>
        <Button variant="contained" startIcon={<AddIcon />} onClick={() => setOpen(true)}>
          New Structure
        </Button>
      </Box>

      {/* Dialog */}
      <Dialog open={open} onClose={() => setOpen(false)}>
        <Box sx={{ p: 3, display: "flex", flexDirection: "column", gap: 2, width: 400 }}>
          <h2>New Structure</h2>

          <TextField
            label="Name"
            variant="outlined"
            fullWidth
            value={name}
            onChange={(e) => setName(e.target.value)}
          />

          <TextField
            label="Description"
            variant="outlined"
            fullWidth
            multiline
            rows={3}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />

          <TextField
            label="Structure File"
            type="file"
            variant="outlined"
            fullWidth
            onChange={handleFileChange}
            inputProps={{ accept: FILE_EXTENSION }}
            InputLabelProps={{ shrink: true }}
          />

          <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
            <Button variant="outlined" onClick={() => setOpen(false)}>
              Cancel
            </Button>
            <Button
              variant="contained"
              onClick={handleUpload}
              disabled={uploadStructureMutation.isLoading}
            >
              {uploadStructureMutation.isLoading ? <CircularProgress size={24} /> : "Upload"}
            </Button>
          </Box>
        </Box>
      </Dialog>
    </>
  );
}