"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, Chip,
  Stack, MenuItem, Select, IconButton, Tooltip, LinearProgress
} from '@mui/material';
import FolderIcon from '@mui/icons-material/Folder';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import DeleteIcon from '@mui/icons-material/Delete';

import { calculateFileHash } from '@/lib/hashing-client';
import { checkDuplicateAction, getFoldersAction, executeBulkItemAction } from '../_actions';

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

export default function BulkUploadPage() {
  const [queue, setQueue] = useState<UploadQueueItem[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isExecuting, setIsExecuting] = useState(false);
  const [dbFolders, setDbFolders] = useState<{id: string, name: string}[]>([]);

  useEffect(() => {
    async function loadFolders() {
      try {
        const folders = await getFoldersAction();
        setDbFolders(folders);
      } catch (err) {
        console.error("Failed to load folders:", err);
      }
    }
    loadFolders();
  }, []);

  const onDrop = useCallback((acceptedFiles: File[]) => {
    const newItems = acceptedFiles.map(file => ({
      id: crypto.randomUUID(),
      file,
      path: (file as any).path || file.name,
      hash: null,
      status: 'queued' as const,
      targetFolderId: "" 
    }));
    setQueue(prev => [...prev, ...newItems]);
  }, []);

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

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

  const removeItem = (id: string) => {
    setQueue(prev => prev.filter(item => item.id !== id));
  };

  const copyFirstRowDestination = () => {
    if (queue.length < 2) return;
    const firstFolderId = queue[0].targetFolderId;
    setQueue(current => current.map(item => ({ ...item, targetFolderId: firstFolderId })));
  };

  useEffect(() => {
    if (!isProcessing) return;
    const runAnalysis = async () => {
      const nextIndex = queue.findIndex(item => item.status === 'queued');
      if (nextIndex === -1) { setIsProcessing(false); return; }

      const item = queue[nextIndex];
      try {
        updateItem(item.id, { status: 'hashing' });
        const hash = await calculateFileHash(item.file);
        updateItem(item.id, { status: 'checking', hash });
        const existing = await checkDuplicateAction(hash);

        updateItem(item.id, { 
          status: existing ? 'duplicate' : 'ready',
          targetFolderId: existing?.parentId || item.targetFolderId 
        });
      } catch (err) {
        updateItem(item.id, { status: 'error' });
      }
    };
    runAnalysis();
  }, [queue, isProcessing]);

  const handleExecute = async () => {
    setIsExecuting(true);
    const itemsToProcess = queue.filter(i => i.status === 'ready' || i.status === 'duplicate');

    const BATCH_SIZE = 3;
    for (let i = 0; i < itemsToProcess.length; i += BATCH_SIZE) {
      const batch = itemsToProcess.slice(i, i + BATCH_SIZE);
      
      await Promise.all(batch.map(async (item) => {
        updateItem(item.id, { status: 'uploading' });
        try {
          const formData = new FormData();
          formData.append("file", item.file);
          formData.append("hash", item.hash || "");
          formData.append("targetFolderId", item.targetFolderId);

          const result = await executeBulkItemAction(formData);
          if (result.success) {
            updateItem(item.id, { status: 'success' });
          } else {
            console.error(`Execution failed for ${item.path}:`, result.error);
            updateItem(item.id, { status: 'error' });
          }
        } catch (error) {
          console.error(`Network error for ${item.path}:`, error);
          updateItem(item.id, { status: 'error' });
        }
      }));
    }
    setIsExecuting(false);
  };

  return (
    <Box sx={{ p: 4, maxWidth: 1400, mx: 'auto' }}>
      <Typography variant="h4" fontWeight={900} gutterBottom color="primary">
        Bulk Upload & Recovery
      </Typography>

      {isExecuting && <LinearProgress sx={{ mb: 2 }} />}

      <Paper 
        {...getRootProps()} 
        sx={{ 
          p: 4, mb: 4, textAlign: 'center', cursor: 'pointer',
          border: '2px dashed', borderColor: isDragActive ? 'primary.main' : 'divider',
          bgcolor: isDragActive ? 'primary.50' : 'grey.50'
        }}
      >
        <input {...getInputProps()} {...({ webkitdirectory: "", directory: "" } as any)} />
        <FolderIcon sx={{ fontSize: 40, color: 'primary.main' }} />
        <Typography>Drag Folders or Files Here</Typography>
      </Paper>

      {queue.length > 0 && (
        <>
          <TableContainer component={Paper} sx={{ mb: 3, maxHeight: 600 }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ width: 50 }} />
                  <TableCell><strong>File Path</strong></TableCell>
                  <TableCell><strong>Status</strong></TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <strong>Destination</strong>
                      <IconButton size="small" onClick={copyFirstRowDestination} color="primary" disabled={isExecuting}>
                        <ContentCopyIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  </TableCell>
                  <TableCell align="right"><strong>Size</strong></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {queue.map((item) => (
                  <TableRow key={item.id} hover>
                    <TableCell>
                      <IconButton 
                        size="small" 
                        color="error" 
                        onClick={() => removeItem(item.id)}
                        disabled={isExecuting || item.status === 'uploading'}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </TableCell>
                    <TableCell sx={{ fontSize: '0.75rem', maxWidth: 300, overflow: 'hidden' }}>
                      {item.path}
                    </TableCell>
                    <TableCell>
                      <Chip 
                        label={item.status.toUpperCase()} 
                        size="small" 
                        color={
                            item.status === 'success' ? 'success' : 
                            item.status === 'duplicate' ? 'warning' : 
                            item.status === 'error' ? 'error' : 'default'
                        } 
                      />
                    </TableCell>
                    <TableCell>
                      <Select
                        value={item.targetFolderId}
                        onChange={(e) => updateItem(item.id, { targetFolderId: e.target.value })}
                        size="small" fullWidth displayEmpty
                        disabled={item.status === 'success' || isExecuting}
                        sx={{ fontSize: '0.8rem' }}
                      >
                        <MenuItem value="">Root Directory</MenuItem>
                        {dbFolders.map(f => <MenuItem key={f.id} value={f.id}>{f.name}</MenuItem>)}
                      </Select>
                    </TableCell>
                    <TableCell align="right">
                      {(item.file.size / 1024 / 1024).toFixed(2)}MB
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>

          <Stack direction="row" spacing={2} justifyContent="flex-end">
            <Button variant="outlined" onClick={() => setQueue([])} disabled={isExecuting}>Clear Queue</Button>
            <Button 
                variant="contained" 
                startIcon={<PlayArrowIcon />}
                onClick={() => setIsProcessing(true)} 
                disabled={isProcessing || isExecuting}
            >
              Analyze
            </Button>
            <Button 
                variant="contained" 
                color="success" 
                startIcon={<CloudUploadIcon />}
                onClick={handleExecute}
                disabled={isProcessing || isExecuting || !queue.some(i => i.status === 'ready' || i.status === 'duplicate')}
            >
              Execute Upload/Restore
            </Button>
          </Stack>
        </>
      )}
    </Box>
  );
}