import { useForm } from '@inertiajs/react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Label } from '@/components/ui/label';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { FormEvent, useState } from 'react';
import {
    Upload,
    FileVideo,
    CheckCircle2,
    AlertCircle,
    Loader2,
    Languages,
    Video,
} from 'lucide-react';

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

export function VideoUploadDialog({ projectId, open, onOpenChange }: VideoUploadDialogProps) {
    const { data, setData, post, processing, errors, reset } = useForm({
        video: null as File | null,
        expected_language: 'auto',
        video_type: 'general',
    });

    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) => {
        const validTypes = ['video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska'];
        if (!validTypes.includes(file.type)) {
            alert('Please select a valid video file (MP4, MOV, AVI, or MKV)');
            return;
        }

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

        setData('video', 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}/videos`, {
            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 Video</DialogTitle>
                    <DialogDescription>
                        Upload a video for AI-powered transcription 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="video-upload"
                            type="file"
                            accept="video/*"
                            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" />
                                        ) : (
                                            <FileVideo className="h-7 w-7 text-muted-foreground" />
                                        )}
                                    </div>
                                    <p className="mt-4 text-sm font-semibold text-foreground">
                                        {dragActive ? 'Drop your video here' : 'Click to upload or drag and drop'}
                                    </p>
                                    <p className="mt-1 text-xs text-muted-foreground">
                                        MP4, MOV, AVI, or MKV files up to 1GB
                                    </p>
                                </>
                            )}
                        </div>
                    </div>

                    {/* Video Type & Language Selectors */}
                    <div className="grid gap-4 sm:grid-cols-2">
                        {/* Video Type */}
                        <div className="space-y-2">
                            <Label htmlFor="video_type" className="flex items-center gap-2 text-sm font-medium">
                                <Video className="h-4 w-4" />
                                Video Type
                            </Label>
                            <Select
                                value={data.video_type}
                                onValueChange={(value) => setData('video_type', value)}
                            >
                                <SelectTrigger id="video_type" className="w-full">
                                    <SelectValue placeholder="Select video type" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="general">General - Broad analysis</SelectItem>
                                    <SelectItem value="meeting">Meeting - Decisions & action items</SelectItem>
                                    <SelectItem value="educational">Educational - Topics & concepts</SelectItem>
                                    <SelectItem value="entertainment">Entertainment - Plot & characters</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Language */}
                        <div className="space-y-2">
                            <Label htmlFor="language" className="flex items-center gap-2 text-sm font-medium">
                                <Languages className="h-4 w-4" />
                                Expected Language
                            </Label>
                            <Select
                                value={data.expected_language}
                                onValueChange={(value) => setData('expected_language', value)}
                            >
                                <SelectTrigger id="language" className="w-full">
                                    <SelectValue placeholder="Select language" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="ro">Romanian (Romana)</SelectItem>
                                    <SelectItem value="en">English</SelectItem>
                                    <SelectItem value="es">Spanish (Espanol)</SelectItem>
                                    <SelectItem value="fr">French (Francais)</SelectItem>
                                    <SelectItem value="de">German (Deutsch)</SelectItem>
                                    <SelectItem value="it">Italian (Italiano)</SelectItem>
                                    <SelectItem value="pt">Portuguese (Portugues)</SelectItem>
                                    <SelectItem value="pl">Polish (Polski)</SelectItem>
                                    <SelectItem value="nl">Dutch (Nederlands)</SelectItem>
                                    <SelectItem value="ru">Russian</SelectItem>
                                    <SelectItem value="zh">Chinese</SelectItem>
                                    <SelectItem value="ja">Japanese</SelectItem>
                                    <SelectItem value="ko">Korean</SelectItem>
                                    <SelectItem value="ar">Arabic</SelectItem>
                                    <SelectItem value="auto">Auto-detect</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    {/* Error Message */}
                    {errors.video && (
                        <Alert variant="destructive">
                            <AlertCircle className="h-4 w-4" />
                            <AlertDescription className="ml-2">{errors.video}</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 video...</p>
                                <p className="mt-1 text-sm">This may take a few moments</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.video || processing} className="gap-2">
                            {processing ? (
                                <>
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                    Uploading...
                                </>
                            ) : (
                                <>
                                    <Upload className="h-4 w-4" />
                                    Upload Video
                                </>
                            )}
                        </Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}
