'use client';
// src/app/upload/upload-view.tsx
import { useState, useRef } from "react";
import { 
  Box, Button, Typography, Paper, Stack, 
  TextField, IconButton, Divider,
  Grid, 
  CircularProgress, Checkbox, MenuItem,
  Collapse,
  Dialog, DialogTitle, DialogContent, 
  DialogContentText, DialogActions 
} from "@mui/material";
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CreateNewFolderIcon from '@mui/icons-material/CreateNewFolder';
import AssignmentIcon from '@mui/icons-material/Assignment';
import ClearIcon from '@mui/icons-material/Clear';
import WarningAmberIcon from '@mui/icons-material/WarningAmber';

import { useRouter } from "next/navigation";
import { getMetadataPreviewAction } from "@/app/dashboard/actions";
import { calculateFileHash } from "@/lib/hashing-client";
import { uploadFileAction, createFolderAction, checkDuplicateAction } from "./_actions";

interface MetadataRow {
  key: string;
  value: string;
  isPending?: boolean; 
  selected?: boolean;  
}

export default function UploadView({ folders }: { user: any; folders: any[] }) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // Form State
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [targetFolderId, setTargetFolderId] = useState<string>("");
  const [showNewFolderInput, setShowNewFolderInput] = useState(false);
  const [newFolderName, setNewFolderName] = useState("");
  const [rows, setRows] = useState<MetadataRow[]>([]);
  
  // UI Status State
  const [isExtracting, setIsExtracting] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'hashing' | 'saving'>('idle');

  // Duplicate Dialog State
  const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
  const [duplicateInfo, setDuplicateInfo] = useState<{ name: string; hash: string } | null>(null);

  const canSubmit = selectedFile !== null || newFolderName.trim().length > 0;

  // --- 1. MAGIC EXTRACTION ---
  const handleMagicEnhance = async () => {
    if (!selectedFile) return;
    setIsExtracting(true);
    try {
      const result = await getMetadataPreviewAction(selectedFile.name); 
      if (result.success) {
        const extractedRows: MetadataRow[] = Object.entries(result.data ?? {}).map(([k, v]) => ({
          key: k,
          value: typeof v === 'object' ? JSON.stringify(v) : String(v),
          isPending: true,
          selected: true 
        }));
        setRows(prev => {
          const existingKeys = new Set(prev.map(r => r.key));
          const newUniqueRows = extractedRows.filter(r => !existingKeys.has(r.key));
          return [...prev, ...newUniqueRows];
        });
      }
    } catch (err) {
      console.error("Extraction failed:", err);
    } finally {
      setIsExtracting(false);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) setSelectedFile(file);
  };

  // --- 2. UPLOAD EXECUTION ---
  const executeUpload = async (preCalculatedHash?: string) => {
    setSaveStatus('saving');
    try {
      let currentParentId = targetFolderId;

      // STEP A: Handle New Folder Creation
      if (newFolderName.trim()) {
        const folderResult = await createFolderAction(newFolderName, targetFolderId || null);
        if (folderResult.success) {
          currentParentId = folderResult.node.id;
        } else {
          throw new Error(folderResult.error || "Failed to create folder");
        }
      }

      // STEP B: Handle File Upload
      if (selectedFile) {
        const formData = new FormData();
        formData.append("file", selectedFile);
        formData.append("hash", preCalculatedHash || ""); 
        formData.append("parentId", currentParentId || "root");
        
        const metadataObject = rows
          .filter(r => r.selected && r.key.trim() !== "")
          .reduce((acc, curr) => {
            acc[curr.key.trim()] = curr.value;
            return acc;
          }, {} as Record<string, string>);

        formData.append("customMetadata", JSON.stringify(metadataObject));

        const uploadResult = await uploadFileAction(formData);
        if (!uploadResult.success) throw new Error(uploadResult.error || "Upload failed");
      }

      router.push("/dashboard");
      router.refresh();
    } catch (err: any) {
      console.error("Save failed:", err);
      alert(err.message || "An error occurred while saving.");
      setSaveStatus('idle');
    }
  };

  // --- 3. SAVE HANDLER (With Hash Intercept) ---
  const handleSave = async () => {
    if (!canSubmit) return;
    
    if (selectedFile) {
      setSaveStatus('hashing');
      // Calculate local SHA-256
      const fileHash = await calculateFileHash(selectedFile);
      // Check database via Server Action
      const duplicate = await checkDuplicateAction(fileHash);

      if (duplicate) {
        setDuplicateInfo({ name: duplicate.name, hash: fileHash });
        setDuplicateDialogOpen(true);
        return; // Dialog takes over from here
      }
      
      await executeUpload(fileHash);
    } else {
      await executeUpload(); // Folder only
    }
  };

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

        <Stack spacing={3} sx={{ mt: 4, mb: 4 }}>
          {/* FOLDER SELECTION */}
          <Box>
            <Stack direction="row" spacing={1}>
              <TextField
                select fullWidth label="Parent Destination"
                value={targetFolderId}
                onChange={(e) => setTargetFolderId(e.target.value)}
                helperText="Choose where your file will live"
              >
                <MenuItem value=""><em>-- Root Directory --</em></MenuItem>
                {folders?.map((f) => (
                  <MenuItem key={f.id} value={f.id}>{f.name}</MenuItem>
                ))}
              </TextField>
              <Button 
                variant={showNewFolderInput ? "contained" : "outlined"} 
                onClick={() => setShowNewFolderInput(!showNewFolderInput)}
                sx={{ height: 56, minWidth: 56 }}
              >
                <CreateNewFolderIcon />
              </Button>
            </Stack>

            <Collapse in={showNewFolderInput}>
              <Box sx={{ mt: 2, p: 2, bgcolor: 'grey.50', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
                <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
                  NEW SUB-FOLDER NAME
                </Typography>
                <TextField
                  fullWidth size="small" placeholder="e.g. Finance 2026"
                  value={newFolderName}
                  onChange={(e) => setNewFolderName(e.target.value)}
                />
              </Box>
            </Collapse>
          </Box>

          {/* FILE SELECTION */}
          <Box>
            <input
              type="file" id="file-upload-input" style={{ display: 'none' }}
              onChange={handleFileChange} ref={fileInputRef}
            />
            {!selectedFile ? (
              <Button
                variant="outlined" fullWidth startIcon={<CloudUploadIcon />}
                onClick={() => fileInputRef.current?.click()}
                sx={{ py: 4, borderStyle: 'dashed', borderWidth: 2, borderRadius: 2 }}
              >
                Select File to Upload
              </Button>
            ) : (
              <Paper variant="outlined" sx={{ p: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between', bgcolor: 'primary.50' }}>
                <Stack direction="row" spacing={2} alignItems="center">
                  <CloudUploadIcon color="primary" />
                  <Typography variant="body1" fontWeight="600">{selectedFile.name}</Typography>
                </Stack>
                <IconButton onClick={() => setSelectedFile(null)} color="error" size="small">
                  <ClearIcon />
                </IconButton>
              </Paper>
            )}
          </Box>
        </Stack>

        <Divider sx={{ my: 4 }} />

        {/* MAGIC EXTRACT */}
        <Box sx={{ mb: 4, p: 2.5, bgcolor: '#f0f7ff', borderRadius: 2, border: '1px dashed #1976d2' }}>
          <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
            <Box>
              <Typography variant="subtitle1" fontWeight="bold" color="primary.main">Magic Extract</Typography>
              <Typography variant="caption" color="text.secondary">
                Auto-pull metadata from file content.
              </Typography>
            </Box>
            <Button 
              variant="contained" onClick={handleMagicEnhance} 
              disabled={!selectedFile || isExtracting}
              startIcon={isExtracting ? <CircularProgress size={20} color="inherit" /> : <AutoFixHighIcon />}
              sx={{ borderRadius: 20, px: 3 }}
            >
              {isExtracting ? "Extracting..." : "Run"}
            </Button>
          </Stack>
        </Box>

        {/* METADATA PREVIEW */}
        <Box sx={{ mb: 4 }}>
          <Typography variant="h6" fontWeight="700" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <AssignmentIcon color="primary" /> Metadata Fields
          </Typography>
          <Stack spacing={2}>
            {rows.map((row, index) => (
              <Grid container spacing={1} key={index} alignItems="center">
                <Grid item xs={1}>
                  <Checkbox checked={row.selected} size="small" onChange={(e) => {
                    const updated = [...rows];
                    updated[index].selected = e.target.checked;
                    setRows(updated);
                  }} />
                </Grid>
                <Grid item xs={5}>
                  <TextField fullWidth size="small" label="Key" value={row.key} onChange={(e) => {
                    const updated = [...rows];
                    updated[index].key = e.target.value;
                    setRows(updated);
                  }} />
                </Grid>
                <Grid item xs={5}>
                  <TextField fullWidth size="small" label="Value" value={row.value} onChange={(e) => {
                    const updated = [...rows];
                    updated[index].value = e.target.value;
                    setRows(updated);
                  }} />
                </Grid>
                <Grid item xs={1}>
                  <IconButton onClick={() => setRows(rows.filter((_, i) => i !== index))} color="error">
                    <DeleteOutlineIcon />
                  </IconButton>
                </Grid>
              </Grid>
            ))}
            <Button variant="text" startIcon={<AddCircleOutlineIcon />} onClick={() => setRows([...rows, {key: "", value: "", selected: true}])}>
              Add Manual Field
            </Button>
          </Stack>
        </Box>

        {/* FINAL BUTTON */}
        <Button 
          variant="contained" size="large" fullWidth onClick={handleSave}
          disabled={!canSubmit || saveStatus !== 'idle'}
          sx={{ py: 2, fontWeight: 'bold', borderRadius: 2, boxShadow: 4 }}
        >
          {saveStatus === 'hashing' ? <CircularProgress size={24} color="inherit" /> : 
           saveStatus === 'saving' ? "Uploading to OneDrive..." : 
           "Complete Upload & Save"}
        </Button>
      </Paper>

      {/* --- DUPLICATE ALERT DIALOG --- */}
      <Dialog
       open={duplicateDialogOpen}
  onClose={() => { setDuplicateDialogOpen(false); setSaveStatus('idle'); }}
  PaperProps={{ sx: { borderRadius: 3, p: 1, maxWidth: 450 } }}
>
  <DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1, color: 'warning.dark', fontWeight: 'bold' }}>
    <WarningAmberIcon fontSize="large" /> Duplicate Content
  </DialogTitle>
  <DialogContent>
    {/* FIX: Added component="div" here. 
        This prevents the "<div> cannot be a descendant of <p>" error 
    */}
    <DialogContentText component="div">
      The file you selected has exactly the same content as a file already in your library:
      
      <Box sx={{ mt: 2, p: 2, bgcolor: 'warning.50', border: '1px solid', borderColor: 'warning.light', borderRadius: 2, color: 'text.primary', fontWeight: '600' }}>
        {duplicateInfo?.name}
      </Box>

      <Typography variant="body2" sx={{ mt: 2, color: 'text.secondary' }}>
        Would you like to skip this upload or create a second copy?
      </Typography>
    </DialogContentText>
  </DialogContent>
  <DialogActions sx={{ p: 2, gap: 1 }}>
    <Button 
      onClick={() => { setDuplicateDialogOpen(false); setSaveStatus('idle'); }} 
      variant="outlined" color="inherit" fullWidth
    >
      Cancel
    </Button>
    <Button 
      onClick={() => { setDuplicateDialogOpen(false); executeUpload(duplicateInfo?.hash); }} 
      variant="contained" color="warning" fullWidth
    >
      Upload Anyway
    </Button>
  </DialogActions>
      </Dialog>
    </>
  );
}