'use client';

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

/**
 * Format bytes to human readable string (MiB/KiB)
 */
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

interface Folder {
  id: string;
  name: string;
  parentId: string | null;
}

interface UploadViewProps {
  user: any;
  folders?: Folder[];
}

export default function UploadView({ user, folders = [] }: UploadViewProps) {
  const router = useRouter();
  
  // Form State
  const [file, setFile] = useState<File | null>(null);
  const [description, setDescription] = useState("");
  const [parentId, setParentId] = useState("");
  const [status, setStatus] = useState<'idle' | 'uploading' | 'success'>('idle');

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

  const MAX_FILE_SIZE = 150 * 1024 * 1024; // 150MB Limit

  const handleCreateFolder = async () => {
    if (!newFolderName.trim()) return;
    setIsCreatingFolder(true);
    try {
      // Creates folder nested under current selection if parentId exists
      await createFolderAction(newFolderName, parentId || null);
      setNewFolderName("");
      setShowFolderInput(false);
      router.refresh(); 
    } catch (err) {
      alert("Error creating folder");
    } finally {
      setIsCreatingFolder(false);
    }
  };

  const handleUpload = async () => {
    if (!file) return;
    if (file.size > MAX_FILE_SIZE) {
      alert(`File is too large! Max allowed: ${formatFileSize(MAX_FILE_SIZE)}.`);
      return;
    }

    setStatus('uploading');
    const formData = new FormData();
    formData.append("file", file);
    formData.append("description", description);
    formData.append("parentId", parentId);

    try {
      const result = await uploadFileAction(formData);
      if (result.success) {
        setStatus('success');
        setFile(null);
        setDescription("");
        router.refresh();
      }
    } catch (err) {
      console.error(err);
      alert("Upload failed. Check server logs.");
      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 }}>
        
        {/* Section 1: Destination Folder */}
        <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
              select
              fullWidth
              label="Target Project / Folder"
              value={parentId}
              onChange={(e) => setParentId(e.target.value)}
              disabled={status === 'uploading'}
              helperText="Files will be virtually organized into this folder."
            >
              <MenuItem value=""><em>-- Root (Main Library) --</em></MenuItem>
              {folders.map((f) => (
                <MenuItem key={f.id} value={f.id} sx={{ pl: f.parentId ? 4 : 2 }}>
                  {f.parentId ? `↳ ${f.name}` : f.name}
                </MenuItem>
              ))}
            </TextField>
            <Tooltip title="Create New Folder Inside Selected">
              <IconButton 
                color="primary" 
                onClick={() => setShowFolderInput(!showFolderInput)}
                sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 1, width: 56, height: 56 }}
              >
                <CreateNewFolderIcon />
              </IconButton>
            </Tooltip>
          </Stack>

          {showFolderInput && (
            <Stack direction="row" spacing={1} sx={{ mt: 2, p: 2, bgcolor: 'action.hover', borderRadius: 2 }}>
              <TextField 
                size="small" 
                fullWidth 
                placeholder="New folder name..." 
                value={newFolderName}
                onChange={(e) => setNewFolderName(e.target.value)}
                autoFocus
                disabled={isCreatingFolder}
              />
              <Button 
                variant="contained" 
                onClick={handleCreateFolder}
                disabled={isCreatingFolder || !newFolderName.trim()}
              >
                {isCreatingFolder ? "..." : "Create"}
              </Button>
            </Stack>
          )}
        </Box>

        <Divider />

        {/* Section 2: File Upload Area */}
        <Box>
          <Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <CloudUploadIcon color="primary" /> 2. Upload File
          </Typography>
          
          <Box 
            sx={{ 
              p: 5, 
              mt: 1,
              border: '2px dashed', 
              borderColor: file ? 'primary.main' : 'divider', 
              borderRadius: 3, 
              textAlign: 'center', 
              bgcolor: file ? 'rgba(25, 118, 210, 0.04)' : '#fafafa',
              '&:hover': { bgcolor: 'rgba(0, 0, 0, 0.02)' }
            }}
          >
            <input 
              type="file" id="file-input" hidden 
              onChange={(e) => {
                setFile(e.target.files?.[0] || null);
                setStatus('idle');
              }} 
            />
            <label htmlFor="file-input">
              <Button 
                variant={file ? "outlined" : "contained"} 
                component="span" 
                startIcon={<CloudUploadIcon />}
                size="large"
                disabled={status === 'uploading'}
              >
                {file ? "Change File" : "Choose Document"}
              </Button>
            </label>
            
            {file && (
              <Box mt={2}>
                <Typography variant="subtitle2" color="primary.main" fontWeight="bold">
                  {file.name}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  {formatFileSize(file.size)}
                </Typography>
              </Box>
            )}
          </Box>
        </Box>

        {/* Section 3: Notes */}
        <Box>
          <Typography variant="h6" gutterBottom fontWeight="700" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <AssignmentIcon color="primary" /> 3. Metadata
          </Typography>
          <TextField
            label="Description / Notes"
            multiline rows={3} fullWidth
            placeholder="Add keywords or a brief summary..."
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            disabled={status === 'uploading'}
          />
        </Box>

        {/* Progress & Actions */}
        <Box>
          {status === 'uploading' && (
            <Box mb={2}>
              <LinearProgress sx={{ borderRadius: 5, height: 10 }} />
              <Typography variant="caption" color="primary" sx={{ mt: 1, display: 'block', textAlign: 'center' }}>
                Transferring to OneDrive and updating Library...
              </Typography>
            </Box>
          )}

          <Button 
            variant="contained" size="large" fullWidth
            disabled={!file || status === 'uploading'}
            onClick={handleUpload}
            sx={{ py: 2, fontWeight: 'bold' }}
          >
            {status === 'uploading' ? 'Uploading...' : 'Add to Library'}
          </Button>

          {status === 'success' && (
            <Typography align="center" color="success.main" fontWeight="bold" sx={{ mt: 2 }}>
              ✅ File processed and assigned to project!
            </Typography>
          )}
        </Box>
      </Stack>
    </Paper>
  );
}