import { useForm } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { FormEvent, useState } from 'react';
import {
    Upload,
    FileText,
    CheckCircle2,
    AlertCircle,
    Loader2,
} from 'lucide-react';

interface DocumentUploadDialogProps {
    projectId: number;
    open: boolean;
    onOpenChange: (open: boolean) => void;
}

const SUPPORTED_EXTENSIONS = [
    'pdf', 'docx', 'doc', 'txt', 'md', 'html', 'csv',
    'xlsx', 'pptx', 'rtf', 'odt', 'json', 'xml',
    'png', 'jpg', 'jpeg', 'tiff'
];

const SUPPORTED_MIME_TYPES = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'text/plain',
    'text/markdown',
    'text/html',
    'text/csv',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/rtf',
    'application/vnd.oasis.opendocument.text',
    'application/json',
    'application/xml',
    'text/xml',
    'image/png',
    'image/jpeg',
    'image/tiff',
];

export function DocumentUploadDialog({ projectId, open, onOpenChange }: DocumentUploadDialogProps) {
    const { data, setData, post, processing, errors, reset } = useForm({
        document: null as File | null,
    });

    const [preview, setPreview] = useState<string | null>(null);
    const [fileSize, setFileSize] = useState<number>(0);
    const [dragActive, setDragActive] = useState(false);

    const handleDrag = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        if (e.type === 'dragenter' || e.type === 'dragover') {
            setDragActive(true);
        } else if (e.type === 'dragleave') {
            setDragActive(false);
        }
    };

    const handleDrop = (e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setDragActive(false);

        if (e.dataTransfer.files && e.dataTransfer.files[0]) {
            handleFile(e.dataTransfer.files[0]);
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            handleFile(e.target.files[0]);
        }
    };

    const handleFile = (file: File) => {
        // Check extension
        const extension = file.name.split('.').pop()?.toLowerCase() || '';
        if (!SUPPORTED_EXTENSIONS.includes(extension)) {
            alert(`Unsupported file type. Supported: ${SUPPORTED_EXTENSIONS.join(', ')}`);
            return;
        }

        // Check MIME type (with fallback for some file types)
        if (file.type && !SUPPORTED_MIME_TYPES.includes(file.type)) {
            // Allow if extension is valid (some browsers report wrong MIME types)
            console.warn('MIME type not in allowed list, but extension is valid:', file.type);
        }

        const maxSize = 500 * 1024 * 1024; // 500MB
        if (file.size > maxSize) {
            alert('File size must be less than 500MB');
            return;
        }

        setData('document', file);
        setPreview(file.name);
        setFileSize(file.size);
    };

    const formatBytes = (bytes: number): string => {
        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 Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
    };

    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();
        post(`/projects/${projectId}/documents`, {
            forceFormData: true,
            onSuccess: () => {
                reset();
                setPreview(null);
                setFileSize(0);
                onOpenChange(false);
            },
        });
    };

    const handleClose = () => {
        if (!processing) {
            reset();
            setPreview(null);
            setFileSize(0);
            onOpenChange(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent className="max-w-2xl">
                <DialogHeader>
                    <DialogTitle>Upload Document</DialogTitle>
                    <DialogDescription>
                        Upload a document for AI-powered processing and analysis
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={handleSubmit} className="space-y-6">
                    {/* Drag & Drop Zone */}
                    <div
                        className={`group relative overflow-hidden rounded-xl border-2 border-dashed transition-all ${
                            dragActive
                                ? 'border-primary bg-primary/5 shadow-lg'
                                : preview
                                  ? 'border-green-500 bg-green-50 dark:border-green-700 dark:bg-green-950/20'
                                  : 'border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/50'
                        }`}
                        onDragEnter={handleDrag}
                        onDragLeave={handleDrag}
                        onDragOver={handleDrag}
                        onDrop={handleDrop}
                    >
                        <input
                            id="document-upload"
                            type="file"
                            accept={SUPPORTED_EXTENSIONS.map(ext => `.${ext}`).join(',')}
                            onChange={handleChange}
                            className="absolute inset-0 z-10 h-full w-full cursor-pointer opacity-0"
                        />

                        <div className="relative p-8 text-center">
                            {preview ? (
                                <>
                                    <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/30">
                                        <CheckCircle2 className="h-6 w-6 text-green-600 dark:text-green-400" />
                                    </div>
                                    <p className="mt-3 text-sm font-semibold text-green-700 dark:text-green-300">
                                        File selected
                                    </p>
                                    <div className="mt-2 space-y-1">
                                        <p className="text-sm font-medium text-foreground">{preview}</p>
                                        <p className="text-xs text-muted-foreground">{formatBytes(fileSize)}</p>
                                    </div>
                                    <p className="mt-3 text-xs text-muted-foreground">
                                        Click or drag another file to replace
                                    </p>
                                </>
                            ) : (
                                <>
                                    <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted transition-transform group-hover:scale-110">
                                        {dragActive ? (
                                            <Upload className="h-7 w-7 text-primary" />
                                        ) : (
                                            <FileText className="h-7 w-7 text-muted-foreground" />
                                        )}
                                    </div>
                                    <p className="mt-4 text-sm font-semibold text-foreground">
                                        {dragActive ? 'Drop your document here' : 'Click to upload or drag and drop'}
                                    </p>
                                    <p className="mt-1 text-xs text-muted-foreground">
                                        PDF, Word, Excel, PowerPoint, Text, Markdown, and more
                                    </p>
                                    <p className="mt-1 text-xs text-muted-foreground">
                                        Images (PNG, JPG, TIFF) will be processed with OCR
                                    </p>
                                </>
                            )}
                        </div>
                    </div>

                    {/* Supported file types info */}
                    <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs font-medium text-muted-foreground">Supported file types:</p>
                        <p className="mt-1 text-xs text-muted-foreground">
                            PDF, Word (DOCX, DOC), Excel (XLSX), PowerPoint (PPTX), Text (TXT),
                            Markdown (MD), HTML, CSV, RTF, JSON, XML, Images with OCR (PNG, JPG, TIFF)
                        </p>
                    </div>

                    {/* Error Message */}
                    {errors.document && (
                        <Alert variant="destructive">
                            <AlertCircle className="h-4 w-4" />
                            <AlertDescription className="ml-2">{errors.document}</AlertDescription>
                        </Alert>
                    )}

                    {/* Processing State */}
                    {processing && (
                        <Alert className="border-blue-200 bg-blue-50 dark:border-blue-900/50 dark:bg-blue-950/20">
                            <Loader2 className="h-5 w-5 animate-spin text-blue-600 dark:text-blue-400" />
                            <AlertDescription className="ml-2 text-blue-800 dark:text-blue-200">
                                <p className="font-semibold">Uploading your document...</p>
                                <p className="mt-1 text-sm">Processing will continue in the background</p>
                            </AlertDescription>
                        </Alert>
                    )}

                    {/* Action Buttons */}
                    <div className="flex justify-end gap-3">
                        <Button type="button" variant="outline" onClick={handleClose} disabled={processing}>
                            Cancel
                        </Button>
                        <Button type="submit" disabled={!data.document || processing} className="gap-2">
                            {processing ? (
                                <>
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                    Uploading...
                                </>
                            ) : (
                                <>
                                    <Upload className="h-4 w-4" />
                                    Upload Document
                                </>
                            )}
                        </Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}
