'use client';

import { useState, useRef } from "react";
import { 
  Box, Button, Typography, Paper, Stack, 
  TextField, MenuItem, IconButton, Divider,
  Grid, CircularProgress
} from "@mui/material";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import FolderIcon from "@mui/icons-material/Folder";
import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder";
import AssignmentIcon from '@mui/icons-material/Assignment';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import { useRouter } from "next/navigation";
import { uploadFileAction, createFolderAction } from "./_actions";

interface MetadataPair {
  key: string;
  value: string;
}

export default function UploadView({ user, folders = [] }: any) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [file, setFile] = useState<File | null>(null);
  const [description, setDescription] = useState("");
  const [parentId, setParentId] = useState("");
  const [status, setStatus] = useState<'idle' | 'uploading' | 'success'>('idle');
  const [customMetadata, setCustomMetadata] = useState<MetadataPair[]>([]);

  // Folder Creation State
  const [showFolderInput, setShowFolderInput] = useState(false);
  const [newFolderName, setNewFolderName] = useState("");
  const [isCreatingFolder, setIsCreatingFolder] = useState(false);

  const handleCreateFolder = async () => {
    if (!newFolderName.trim()) return;
    setIsCreatingFolder(true);
    try {
      // FIX: Pass the current parentId to the action so it nests correctly
      const result = await createFolderAction(newFolderName, parentId);
      if (result.success) {
        setNewFolderName("");
        setShowFolderInput(false);
        router.refresh(); 
      }
    } catch (err: any) {
      alert(err.message || "Failed to create folder");
    } finally {
      setIsCreatingFolder(false);
    }
  };

  const addMetadataRow = () => setCustomMetadata([...customMetadata, { key: "", value: "" }]);
  
  const removeMetadataRow = (index: number) => {
    setCustomMetadata(customMetadata.filter((_, i) => i !== index));
  };

  const updateMetadataRow = (index: number, field: 'key' | 'value', val: string) => {
    const updated = [...customMetadata];
    updated[index][field] = val;
    setCustomMetadata(updated);
  };

  const handleUpload = async () => {
    if (!file) return;
    setStatus('uploading');

    const formData = new FormData();
    formData.append("file", file);
    formData.append("description", description);
    formData.append("parentId", parentId);
    
    const metadataObj = customMetadata.reduce((acc, curr) => {
      if (curr.key.trim()) acc[curr.key.trim()] = curr.value;
      return acc;
    }, {} as Record<string, string>);
    
    formData.append("customMetadata", JSON.stringify(metadataObj));

    try {
      const result = await uploadFileAction(formData);
      if (result.success) {
        setStatus('success');
        setFile(null);
        setDescription("");
        setCustomMetadata([]);
        router.push("/dashboard");
        router.refresh();
      }
    } catch (err) {
      alert("Upload failed.");
      setStatus('idle');
    }
  };

  return (
    <Paper sx={{ p: { xs: 3, md: 6 }, borderRadius: 4, maxWidth: 800, mx: 'auto' }} elevation={3}>
      <Typography variant="h4" fontWeight={900} color="primary" gutterBottom align="center">
        Add to Library
      </Typography>

      <Stack spacing={4} sx={{ mt: 4 }}>
        {/* 1. Destination */}
        <Box>
          <Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <FolderIcon color="primary" /> 1. Destination
          </Typography>
          
          <Stack direction="row" spacing={1}>
            <TextField
              id="project-destination-select"
              select
              fullWidth
              label="Target Project / Folder"
              value={parentId}
              onChange={(e) => setParentId(e.target.value)}
              size="small"
              slotProps={{
                select: { displayEmpty: true },
                inputLabel: { shrink: true },
              }}
            >
              <MenuItem value=""><em>-- Root (Main Folder) --</em></MenuItem>
              {folders.map((f: any) => (
                <MenuItem key={f.id} value={f.id}>{f.name}</MenuItem>
              ))}
            </TextField>
            <IconButton 
              color="primary" 
              onClick={() => setShowFolderInput(!showFolderInput)} 
              sx={{ border: '1px solid #ccc', borderRadius: 1 }}
            >
              <CreateNewFolderIcon />
            </IconButton>
          </Stack>

          {showFolderInput && (
            <Box sx={{ mt: 2, p: 2, bgcolor: '#f8f9fa', borderRadius: 2 }}>
              <Typography variant="subtitle2" gutterBottom>
                {parentId ? `Create inside current selection` : `Create at Root`}
              </Typography>
              <Stack direction="row" spacing={1}>
                <TextField 
                  fullWidth size="small" placeholder="Folder Name (e.g. Project-2)" 
                  value={newFolderName}
                  onChange={(e) => setNewFolderName(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleCreateFolder()}
                />
                <Button 
                  variant="contained" 
                  onClick={handleCreateFolder}
                  disabled={isCreatingFolder || !newFolderName}
                >
                  {isCreatingFolder ? <CircularProgress size={24} /> : "Create"}
                </Button>
              </Stack>
            </Box>
          )}
        </Box>

        {/* 2. Upload Area */}
        <Box>
          <Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <CloudUploadIcon color="primary" /> 2. Upload File
          </Typography>
          
          <input 
            type="file" 
            ref={fileInputRef} 
            style={{ display: 'none' }} 
            onChange={(e) => setFile(e.target.files?.[0] || null)} 
          />
          
          <Button 
            variant="outlined" 
            fullWidth 
            sx={{ p: 4, borderStyle: 'dashed', textTransform: 'none' }}
            onClick={() => fileInputRef.current?.click()}
          >
            {file ? (
              <Box>
                <Typography color="success.main" fontWeight="bold">✓ {file.name}</Typography>
                <Typography variant="caption" color="text.secondary">
                  Click to change file ({(file.size / 1024 / 1024).toFixed(2)} MB)
                </Typography>
              </Box>
            ) : (
              "Click to Select File"
            )}
          </Button>
        </Box>

        {/* 3. Custom Attributes */}
        <Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
            <Typography variant="h6" fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <AssignmentIcon color="primary" /> 3. Custom Attributes
            </Typography>
            <Button startIcon={<AddCircleOutlineIcon />} size="small" onClick={addMetadataRow}>
              Add Field
            </Button>
          </Box>
          
          <Stack spacing={2}>
            {customMetadata.map((row, index) => (
              <Grid container spacing={1} key={index} alignItems="center">
                <Grid item xs={5}>
                  <TextField 
                    fullWidth size="small" placeholder="Key (e.g. Project-ID)" 
                    value={row.key} onChange={(e) => updateMetadataRow(index, 'key', e.target.value)}
                  />
                </Grid>
                <Grid item xs={6}>
                  <TextField 
                    fullWidth size="small" placeholder="Value" 
                    value={row.value} onChange={(e) => updateMetadataRow(index, 'value', e.target.value)}
                  />
                </Grid>
                <Grid item xs={1}>
                  <IconButton color="error" onClick={() => removeMetadataRow(index)}>
                    <DeleteOutlineIcon />
                  </IconButton>
                </Grid>
              </Grid>
            ))}
            
            <TextField
              label="General Description"
              multiline rows={2} fullWidth
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </Stack>
        </Box>

        <Button 
          variant="contained" size="large" fullWidth
          disabled={!file || status === 'uploading'}
          onClick={handleUpload}
          sx={{ py: 2, fontWeight: 'bold' }}
        >
          {status === 'uploading' ? 'Uploading to OneDrive...' : 'Start Upload'}
        </Button>
      </Stack>
    </Paper>
  );
}