// src/app/upload/bulk/page.tsx

"use client";

import React, { useState, useCallback, useEffect } from 'react';
import { useDropzone } from 'react-dropzone';
import { 
  Box, Button, Typography, Paper, Table, TableBody, 
  TableCell, TableContainer, TableHead, TableRow, LinearProgress, Chip,
  Alert, Stack
} from '@mui/material';
import FolderIcon from '@mui/icons-material/Folder';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';

// --- OUR UTILITIES ---
import { calculateFileHash } from '@/lib/hashing-client';
import { checkDuplicateAction } from '../_actions';

interface UploadQueueItem {
  id: string;
  file: File;
  path: string;
  hash: string | null;
  status: 'queued' | 'hashing' | 'checking' | 'ready' | 'uploading' | 'success' | 'duplicate' | 'error';
  error?: string;
}

export default function BulkUploadPage() {
  const [queue, setQueue] = useState<UploadQueueItem[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);

  // 1. Handle File & Folder Drops
  const onDrop = useCallback((acceptedFiles: File[]) => {
    const newItems = acceptedFiles.map(file => ({
      id: crypto.randomUUID(),
      file,
      path: (file as any).path || file.name, // Captures subfolder structure
      hash: null,
      status: 'queued' as const,
    }));
    setQueue(prev => [...prev, ...newItems]);
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  // 2. The "Processing Engine"
  // This effect runs whenever the queue changes or isProcessing toggles
  useEffect(() => {
    if (!isProcessing) return;

    const runQueue = async () => {
      // Find the next file that hasn't been hashed/checked yet
      const nextIndex = queue.findIndex(item => item.status === 'queued');
      
      if (nextIndex === -1) {
        setIsProcessing(false);
        return; 
      }

      const item = queue[nextIndex];
      
      try {
        // Step A: Hashing
        updateItem(item.id, { status: 'hashing' });
        const hash = await calculateFileHash(item.file);

        // Step B: Duplicate Check
        updateItem(item.id, { status: 'checking', hash });
        const existing = await checkDuplicateAction(hash);

        // Step C: Mark Results
        updateItem(item.id, { 
          status: existing ? 'duplicate' : 'ready' 
        });
      } catch (err) {
        updateItem(item.id, { status: 'error', error: 'Process failed' });
      }
    };

    runQueue();
  }, [queue, isProcessing]);

  const updateItem = (id: string, updates: Partial<UploadQueueItem>) => {
    setQueue(current => current.map(item => item.id === id ? { ...item, ...updates } : item));
  };

  const duplicateCount = queue.filter(i => i.status === 'duplicate').length;

  return (
    <Box sx={{ p: 4, maxWidth: 1200, mx: 'auto' }}>
      <Typography variant="h4" fontWeight={800} color="primary" gutterBottom>
        Bulk Uploads & Restore
      </Typography>

      <Paper 
        {...getRootProps()} 
        sx={{ 
          p: 6, mb: 4, textAlign: 'center', cursor: 'pointer',
          border: '2px dashed', borderColor: isDragActive ? 'primary.main' : 'divider',
          bgcolor: isDragActive ? 'primary.50' : 'background.paper',
          transition: 'all 0.2s'
        }}
      >
        <input {...getInputProps()} {...({ webkitdirectory: "", directory: "" } as any)} />
        <FolderIcon sx={{ fontSize: 64, color: 'primary.main', mb: 2 }} />
        <Typography variant="h6">Drop Folders or Files Here</Typography>
        <Typography variant="body2" color="text.secondary">
          Perfect for camera imports or full system restores
        </Typography>
      </Paper>

      {duplicateCount > 0 && (
        <Alert severity="warning" sx={{ mb: 3 }}>
          {duplicateCount} duplicate(s) found. These files already exist in your library.
        </Alert>
      )}

      {queue.length > 0 && (
        <TableContainer component={Paper} sx={{ maxHeight: 500, borderRadius: 2 }}>
          <Table stickyHeader size="small">
            <TableHead>
              <TableRow>
                <TableCell>Location / Path</TableCell>
                <TableCell>Size</TableCell>
                <TableCell>Status</TableCell>
                <TableCell>SHA-256 Hash</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {queue.map((item) => (
                <TableRow key={item.id} hover>
                  <TableCell sx={{ fontFamily: 'monospace', fontSize: '0.8rem' }}>
                    {item.path}
                  </TableCell>
                  <TableCell>
                    {(item.file.size / 1024 / 1024).toFixed(2)} MB
                  </TableCell>
                  <TableCell>
                    <Chip 
                      label={item.status.toUpperCase()} 
                      size="small"
                      color={
                        item.status === 'duplicate' ? 'warning' : 
                        item.status === 'ready' ? 'info' : 
                        item.status === 'success' ? 'success' : 'default'
                      }
                    />
                  </TableCell>
                  <TableCell sx={{ fontSize: '0.7rem', color: 'text.secondary' }}>
                    {item.hash ? `${item.hash.substring(0, 16)}...` : '---'}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      <Stack direction="row" spacing={2} sx={{ mt: 4 }}>
        <Button 
          variant="contained" 
          size="large"
          startIcon={isProcessing ? <LinearProgress sx={{ width: 20 }} /> : <CloudUploadIcon />}
          disabled={isProcessing || queue.length === 0}
          onClick={() => setIsProcessing(true)}
        >
          {isProcessing ? 'Analyzing...' : `Analyze ${queue.length} Files`}
        </Button>
        
        <Button 
          variant="outlined" 
          color="inherit"
          disabled={isProcessing}
          onClick={() => setQueue([])}
        >
          Clear All
        </Button>
      </Stack>
    </Box>
  );
}