'use client';

import { useState, useRef } from "react";
import { 
  Box, Button, Typography, Paper, Stack, 
  TextField, IconButton, Divider,
  Grid, 
  CircularProgress, Checkbox, MenuItem,
  InputAdornment, Collapse
} 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 { useRouter } from "next/navigation";
import { getMetadataPreviewAction } from "@/app/dashboard/actions";
import { uploadFileAction, createFolderAction } from "./_actions";

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

export default function UploadView({ user, folders }: { user: any; folders: any[] }) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  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[]>([]);
  const [isExtracting, setIsExtracting] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving'>('idle');

  // Logic to determine if the "Complete" button should be active
  const canSubmit = selectedFile !== null || newFolderName.trim().length > 0;

  // --- 1. MAGIC EXTRACTION LOGIC ---
  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: 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. SAVE / UPLOAD LOGIC ---
  const handleSave = async () => {
    if (!canSubmit) return;
    setSaveStatus('saving');
    
    try {
      let currentParentId = targetFolderId;

      // STEP A: Create Folder if user typed a new folder name
      if (newFolderName.trim()) {
        const folderResult = await createFolderAction(newFolderName, targetFolderId || null);
        if (folderResult.success) {
          // If successful, we want the file to go inside this NEW folder
          currentParentId = folderResult.node.id;
        }
      }

      // STEP B: Upload File if a file is selected
      if (selectedFile) {
        const formData = new FormData();
        formData.append("file", selectedFile);
        formData.append("parentId", currentParentId || "root");
        
        // Construct Metadata Object
        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");
        }
      }

      console.log("✅ Process complete. Returning to dashboard.");
      router.push("/dashboard");
      router.refresh();
    } catch (err: any) {
      console.error("Save failed:", err);
      alert(err.message || "An error occurred while saving.");
    } finally {
      setSaveStatus('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">
        Upload & Enrich
      </Typography>

      <Stack spacing={3} sx={{ mt: 4, mb: 4 }}>
        {/* FOLDER SELECTION */}
        <Box>
          <Stack direction="row" spacing={1}>
            <TextField
              select
              fullWidth
              label="Destination Folder"
              value={targetFolderId}
              onChange={(e) => {
                setTargetFolderId(e.target.value);
                if (e.target.value) setShowNewFolderInput(false);
              }}
            >
              <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);
                if (!showNewFolderInput) setTargetFolderId(""); 
              }}
              sx={{ height: 56, minWidth: 56 }}
            >
              <CreateNewFolderIcon />
            </Button>
          </Stack>

          <Collapse in={showNewFolderInput}>
            <Box sx={{ mt: 2, p: 2, bgcolor: 'grey.50', borderRadius: 2 }}>
              <TextField
                fullWidth 
                size="small" 
                label="New Folder Name"
                placeholder="Enter name to create folder..."
                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 }}
            >
              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="500">{selectedFile.name}</Typography>
              </Stack>
              <IconButton onClick={() => setSelectedFile(null)} color="error">
                <ClearIcon />
              </IconButton>
            </Paper>
          )}
        </Box>
      </Stack>

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

      {/* MAGIC EXTRACT */}
      <Box sx={{ mb: 4, p: 2, bgcolor: '#f0f7ff', borderRadius: 2, border: '1px dashed #1976d2' }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Box>
            <Typography variant="subtitle1" fontWeight="bold">Magic Extract</Typography>
            <Typography variant="caption" color="text.secondary">Populate metadata automatically from file properties.</Typography>
          </Box>
          <Button 
            variant="contained" 
            onClick={handleMagicEnhance} 
            disabled={!selectedFile || isExtracting}
            startIcon={isExtracting ? <CircularProgress size={20} color="inherit" /> : <AutoFixHighIcon />}
          >
            {isExtracting ? "Running..." : "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 Preview
        </Typography>
        <Stack spacing={2}>
          {rows.map((row, index) => (
            <Grid container spacing={1} key={index} alignItems="center">
              <Grid size={1}>
                <Checkbox 
                  checked={row.selected} 
                  onChange={(e) => {
                    const updated = [...rows];
                    updated[index].selected = e.target.checked;
                    setRows(updated);
                  }}
                />
              </Grid>
              <Grid size={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 size={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 size={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>

      {/* UPLOAD BUTTON */}
      <Button 
        variant="contained" 
        size="large" 
        fullWidth
        onClick={handleSave}
        disabled={!canSubmit || saveStatus === 'saving'}
        sx={{ py: 2, fontWeight: 'bold' }}
      >
        {saveStatus === 'saving' ? (
          <Stack direction="row" spacing={2} alignItems="center">
            <CircularProgress size={24} color="inherit" />
            <Typography>Processing Upload...</Typography>
          </Stack>
        ) : (
          "Complete Upload & Save"
        )}
      </Button>
    </Paper>
  );
}