import { useState, useEffect, useRef } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { Loader2, Upload, Play, FileVideo, Download, AlertTriangle, CheckCircle } from 'lucide-react'
import { VideoLearningService } from '@/services/videoLearning'
import { open } from '@tauri-apps/plugin-dialog'
import { convertFileSrc } from '@tauri-apps/api/core'

interface TranscriptSegment {
    from: string; // e.g. "00:00:01,000"
    to: string;
    text: string;
}

interface WhisperJson {
    transcription: Array<{
        timestamps: { from: string, to: string };
        offsets: { from: number, to: number };
        text: string;
    }>;
    // Whisper-cli JSON output format might vary, let's adapt.
    // Usually it's { transcription: [ { text: "...", timestamps: { from: "...", to: "..." } } ] }
}

export const VideoLearningPage = () => {
    const [hasDependencies, setHasDependencies] = useState<boolean | null>(null)
    const [hasModel, setHasModel] = useState<boolean | null>(null)
    const [isDownloading, setIsDownloading] = useState(false)
    const [downloadProgress, setDownloadProgress] = useState(0)

    const [videoPath, setVideoPath] = useState<string | null>(null)
    const [videoSrc, setVideoSrc] = useState<string | null>(null)
    const [isTranscribing, setIsTranscribing] = useState(false)
    const [transcript, setTranscript] = useState<any[] | null>(null)

    // Initial Checks
    useEffect(() => {
        checkSystem()
    }, [])

    const checkSystem = async () => {
        try {
            const deps = await VideoLearningService.checkDependencies()
            setHasDependencies(deps)
            const model = await VideoLearningService.checkModelExists()
            setHasModel(model)
        } catch (e) {
            console.error(e)
        }
    }

    const handleDownloadModel = async () => {
        setIsDownloading(true)
        try {
            await VideoLearningService.downloadModel((current, total) => {
                if (total > 0) setDownloadProgress((current / total) * 100)
            })
            await checkSystem()
        } catch (e) {
            alert("Download failed: " + e)
        } finally {
            setIsDownloading(false)
        }
    }

    const handleSelectVideo = async () => {
        const file = await open({
            multiple: false,
            filters: [{ name: 'Video', extensions: ['mp4', 'mkv', 'mov', 'avi'] }]
        })
        if (file) {
            setVideoPath(file.path)
            setVideoSrc(convertFileSrc(file.path))
            setTranscript(null)
        }
    }

    const handleTranscribe = async () => {
        if (!videoPath) return
        setIsTranscribing(true)
        try {
            const result = await VideoLearningService.transcribeVideo(videoPath)
            // Adapt result based on actual structure
            // Usually result['transcription'] is the array
            setTranscript(result.transcription || [])
        } catch (e) {
            console.error(e)
            alert("Transcription failed. Check console.")
        } finally {
            setIsTranscribing(false)
        }
    }

    if (hasDependencies === false) {
        return (
            <div className="p-12 text-center">
                <Alert variant="destructive" className="max-w-xl mx-auto mb-6">
                    <AlertTriangle className="h-4 w-4" />
                    <AlertTitle>Missing Dependencies</AlertTitle>
                    <AlertDescription>
                        Could not find <code>whisper-cli.exe</code> or <code>ffmpeg.exe</code> in the llama folder.<br />
                        Please install these tools manually to use Video Learning.
                    </AlertDescription>
                </Alert>
            </div>
        )
    }

    return (
        <div className="p-6 max-w-6xl mx-auto min-h-[calc(100vh-4rem)]">
            <h1 className="text-3xl font-bold tracking-tight mb-6">Video Learning</h1>

            {/* Model Check */}
            {hasModel === false && (
                <Card className="p-6 mb-8 border-yellow-500/50 bg-yellow-500/5">
                    <div className="flex items-center gap-4">
                        <div className="p-3 bg-yellow-500/20 rounded-full">
                            <Download className="w-6 h-6 text-yellow-600" />
                        </div>
                        <div className="flex-1">
                            <h3 className="font-semibold text-lg">AI Model Required</h3>
                            <p className="text-muted-foreground">Download the Norwegian Whisper model to start transcribing videos.</p>
                        </div>
                        {isDownloading ? (
                            <div className="w-48 space-y-2">
                                <Progress value={downloadProgress} className="h-2" />
                                <p className="text-xs text-center text-muted-foreground">{Math.round(downloadProgress)}%</p>
                            </div>
                        ) : (
                            <Button onClick={handleDownloadModel}>Download Model (~1.5 GB)</Button>
                        )}
                    </div>
                </Card>
            )}

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Left Col: Player & Controls */}
                <div className="lg:col-span-2 space-y-6">
                    <Card className="aspect-video bg-black flex items-center justify-center overflow-hidden relative group">
                        {videoSrc ? (
                            <div className="w-full h-full">
                                <video
                                    src={videoSrc}
                                    controls
                                    className="w-full h-full object-contain"
                                />
                            </div>
                        ) : (
                            <div className="text-center">
                                <FileVideo className="w-16 h-16 text-muted-foreground mx-auto mb-4 opacity-50" />
                                <p className="text-muted-foreground">No video selected</p>
                                <Button variant="outline" className="mt-4" onClick={handleSelectVideo}>
                                    Select Video
                                </Button>
                            </div>
                        )}
                    </Card>

                    <div className="flex justify-between items-center">
                        <div>
                            {videoPath && <Badge variant="secondary" className="font-mono text-xs">{videoPath.split('\\').pop()}</Badge>}
                        </div>
                        <div className="flex gap-2">
                            <Button variant="outline" onClick={handleSelectVideo}>
                                <Upload className="w-4 h-4 mr-2" /> Change Video
                            </Button>
                            <Button
                                onClick={handleTranscribe}
                                disabled={!hasModel || !videoPath || isTranscribing}
                            >
                                {isTranscribing ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Transcribing...</> : <><Play className="w-4 h-4 mr-2" /> Transcribe</>}
                            </Button>
                        </div>
                    </div>
                </div>

                {/* Right Col: Transcript */}
                <div className="lg:col-span-1">
                    <Card className="h-[600px] flex flex-col">
                        <div className="p-4 border-b bg-muted/30">
                            <h3 className="font-semibold flex items-center gap-2">
                                <CheckCircle className="w-4 h-4 text-primary" /> Transcript
                            </h3>
                        </div>
                        <div className="flex-1 overflow-y-auto p-4 space-y-4">
                            {transcript ? (
                                transcript.map((seg, idx) => (
                                    <div key={idx} className="group hover:bg-muted/50 p-2 rounded transition-colors cursor-pointer">
                                        <div className="text-xs text-muted-foreground font-mono mb-1">{seg.timestamps?.from}</div>
                                        <p className="text-sm leading-relaxed">{seg.text}</p>
                                    </div>
                                ))
                            ) : (
                                <div className="text-center text-muted-foreground py-12">
                                    <p>Transcript will appear here.</p>
                                </div>
                            )}
                        </div>
                    </Card>
                </div>
            </div>
        </div>
    )
}
