"use client"

import { useState, useEffect, useCallback } from "react"
import { useRouter, useParams } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Loader2, TrendingUp } from "lucide-react"
import { PageHeader } from "@/components/page-header"
import { PoweredBy } from "@/components/powered-by"
import {
    loadSession,
} from "@/lib/api"
import { SessionContext } from "@/types"
import { ROUTES } from "@/utils/routes"
import { Button } from "@/components/ui/button"

const API_URL = process.env.NEXT_PUBLIC_API_URL
const WS_URL = API_URL?.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://")

export default function VideoProcessingPage() {
    const router = useRouter()
    const { videoId } = useParams() as { videoId: string }
    const [session, setSession] = useState<SessionContext | null>(null)
    const [isLoading, setIsLoading] = useState(true)

    // Processing states
    const [progress, setProgress] = useState(0)
    const [statusMessage, setStatusMessage] = useState("Initializing...")
    const [error, setError] = useState<string | null>(null)

    const connectWebSocket = useCallback((vid: string) => {
        const ws = new WebSocket(`${WS_URL}/ws/${vid}`)

        ws.onmessage = async (event) => {
            const data = JSON.parse(event.data)

            if (data.type === "progress" || data.progress !== undefined) {
                setProgress(data.progress || 0)
                let message = data.message || "Processing..."
                if (data.unique_potholes !== undefined) {
                    message += ` | Unique: ${data.unique_potholes} | Total: ${data.total_detections || 0}`
                } else if (data.unique_signboards !== undefined) {
                    message += ` | Unique: ${data.unique_signboards} | Total: ${data.total_detections || 0}`
                }
                setStatusMessage(message)
            }

            if (data.type === "complete" || data.status === "completed") {
                setStatusMessage("Processing completed! Finalizing...")
                ws.close()

                // Navigate to results
                setTimeout(() => router.push(`/results/${vid}`), 1000)
            }

            if (data.type === "error") {
                setError("Error: " + data.message)
                setStatusMessage("")
                ws.close()
            }
        }

        ws.onerror = () => {
            setStatusMessage("Connection lost. Reconnecting...")
            setTimeout(() => connectWebSocket(vid), 3000)
        }

        return ws
    }, [router])

    useEffect(() => {
        const storedSession = loadSession()
        setSession(storedSession)

        const checkStatus = async () => {
            try {
                const response = await fetch(`${API_URL}/status/${videoId}`, {
                    headers: { "ngrok-skip-browser-warning": "true" }
                })

                if (response.status === 404) {
                    router.replace(ROUTES.UPLOAD)
                    return
                }

                if (!response.ok) {
                    throw new Error("Failed to fetch status")
                }

                const statusData = await response.json()

                if (statusData.status === "completed") {
                    router.replace(`/results/${videoId}`)
                    return
                }

                if (statusData.status === "error") {
                    setError(statusData.message || "An error occurred during processing.")
                    setIsLoading(false)
                    return
                }

                // If processing, start WebSocket
                setProgress(statusData.progress || 0)
                setStatusMessage(statusData.message || "Resuming processing...")
                connectWebSocket(videoId)
                setIsLoading(false)

            } catch (err) {
                console.error("Status check failed:", err)
                setError("Failed to connect to server.")
                setIsLoading(false)
            }
        }

        if (videoId) {
            checkStatus()
        }
    }, [videoId, router, connectWebSocket])

    if (isLoading) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <Card className="p-8">
                    <Loader2 className="h-8 w-8 animate-spin text-primary" />
                </Card>
            </div>
        )
    }

    return (
        <div className="min-h-screen">
            <main className="min-h-screen flex flex-col">
                <div className="flex-1 container mx-auto px-6 py-6 max-w-340 flex flex-col">
                    <div className="mb-6">
                        <PageHeader
                            title="Processing Analysis"
                            description={`Real-time analysis progress for video ID: ${videoId}`}
                            icon={TrendingUp}
                        />
                    </div>

                    {session && (
                        <div className="mb-6">
                            <Card className="p-0 border shadow-sm overflow-hidden">
                                <div className="flex flex-col md:flex-row md:items-center py-4 px-6 gap-6 bg-card">
                                    <div className="flex flex-wrap items-center gap-x-12 gap-y-4 flex-1">
                                        <div className="flex flex-col">
                                            <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Project</span>
                                            <span className="text-base font-bold leading-tight">
                                                {session.projectName}
                                            </span>
                                        </div>
                                        <div className="flex flex-col border-l pl-12 border-border/60">
                                            <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span>
                                            <span className="text-sm font-semibold text-muted-foreground leading-tight">
                                                {session.packageName}
                                            </span>
                                        </div>
                                        <div className="flex flex-col border-l pl-12 border-border/60">
                                            <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Location</span>
                                            <span className="text-sm font-semibold text-muted-foreground leading-tight">
                                                {session.locationName}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </Card>
                        </div>
                    )}

                    <Card className="flex-1 flex flex-col items-center justify-center py-12 px-8 min-h-[450px]">
                        <div className="flex flex-col items-center justify-center w-full max-w-2xl space-y-10">
                            <div className="text-center space-y-4">
                                <h2 className="text-3xl font-bold tracking-tight">
                                    Processing Analysis
                                </h2>
                                <p className="text-sm font-mono text-muted-foreground tracking-widest">
                                    ID: {videoId}
                                </p>
                            </div>

                            <div className="w-full space-y-4">
                                <div className="flex items-center justify-between text-sm">
                                    <span className="font-bold text-muted-foreground text-xs uppercase tracking-widest">Progress</span>
                                    <span className="font-bold text-primary text-lg">{progress}%</span>
                                </div>
                                <div className="h-4 rounded-full bg-secondary overflow-hidden border">
                                    <div
                                        className="h-full bg-primary transition-all duration-1000 ease-in-out"
                                        style={{ width: `${progress}%` }}
                                    />
                                </div>
                                <div className="text-center pt-2">
                                    <div className="inline-flex items-center gap-3 px-4 py-2 rounded-full border bg-secondary/30">
                                        <Loader2 className="h-4 w-4 animate-spin text-primary" />
                                        <p className="text-sm font-semibold">
                                            {statusMessage}
                                        </p>
                                    </div>
                                </div>
                            </div>

                            {error && (
                                <div className="w-full p-6 rounded-md bg-destructive/10 border border-destructive/20 text-center space-y-3">
                                    <p className="text-destructive font-medium">{error}</p>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => window.location.reload()}
                                    >
                                        Retry Connection
                                    </Button>
                                </div>
                            )}
                        </div>
                    </Card>

                    <PoweredBy />
                </div>
            </main>
        </div>
    )
}
