import { useState, useRef, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router'
import { MOCK_MISSIONS } from '@/lib/mockData'
import { MissionControl } from '../components/sandbox/MissionControl'
import { MissionReportModal } from '../components/sandbox/MissionReportModal'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Send, Sparkles, LogOut } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Watermark } from '@/features/flashcards/components/Watermark'

interface ChatMessage {
    id: string
    role: 'user' | 'assistant'
    content: string
}

export const SandboxPage = () => {
    const { missionId } = useParams()
    const navigate = useNavigate()
    const mission = MOCK_MISSIONS.find(m => m.id === missionId)

    const [messages, setMessages] = useState<ChatMessage[]>([])
    const [inputValue, setInputValue] = useState('')
    const [completedKeywords, setCompletedKeywords] = useState<string[]>([])
    const [showReport, setShowReport] = useState(false)
    const messagesEndRef = useRef<HTMLDivElement>(null)

    // Init mission
    useEffect(() => {
        if (mission) {
            setMessages([
                { id: 'init', role: 'assistant', content: mission.initialPrompt }
            ])
            setCompletedKeywords([])
        }
    }, [mission])

    // Auto-scroll
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
    }, [messages])

    if (!mission) return <div>Mission not found</div>

    const handleSendMessage = (e?: React.FormEvent) => {
        e?.preventDefault()
        if (!inputValue.trim()) return

        const newMessage: ChatMessage = {
            id: Date.now().toString(),
            role: 'user',
            content: inputValue
        }

        setMessages(prev => [...prev, newMessage])
        setInputValue('')

        // Check for keywords
        const lowerInput = inputValue.toLowerCase()
        const newKeywords = mission.keywords.filter(k =>
            lowerInput.includes(k.toLowerCase()) && !completedKeywords.includes(k.toLowerCase())
        )
        if (newKeywords.length > 0) {
            setCompletedKeywords(prev => [...prev, ...newKeywords])
        }

        // Mock AI response
        setTimeout(() => {
            setMessages(prev => [...prev, {
                id: (Date.now() + 1).toString(),
                role: 'assistant',
                content: "Det forstår jeg. Vil du ha noe annet?"
            }])
        }, 1000)
    }

    const handleEndMission = () => {
        setShowReport(true)
    }

    return (
        <div className="flex h-[calc(100vh-4rem)] overflow-hidden relative">
            <Watermark text="mission" size="lg" className="opacity-5 z-0" />

            {/* Left Panel: Mission Control */}
            <div className="w-1/3 min-w-[320px] h-full border-r bg-card/60 backdrop-blur-sm hidden md:block relative z-10 shadow-xl">
                <MissionControl
                    mission={mission}
                    completedKeywords={completedKeywords}
                />
            </div>

            {/* Right Panel: Chat Interface */}
            <div className="flex-1 flex flex-col h-full bg-transparent relative z-10">
                {/* Header Overlay */}
                <div className="absolute top-4 right-4 z-20 flex gap-2">
                    <Button variant="destructive" size="sm" className="shadow-lg hover:shadow-xl transition-all" onClick={handleEndMission}>
                        <LogOut className="w-4 h-4 mr-2" /> End Mission
                    </Button>
                </div>

                <div className="flex-1 overflow-y-auto p-6 space-y-6 pb-24 scroll-smooth">
                    {messages.map((msg) => (
                        <div
                            key={msg.id}
                            className={cn(
                                "flex w-full animate-in slide-in-from-bottom-2 duration-300",
                                msg.role === 'user' ? "justify-end" : "justify-start"
                            )}
                        >
                            <div
                                className={cn(
                                    "max-w-[80%] rounded-2xl px-6 py-4 shadow-md text-base leading-relaxed relative",
                                    msg.role === 'user'
                                        ? "bg-primary text-primary-foreground rounded-br-sm shadow-primary/20"
                                        : "bg-card text-card-foreground rounded-bl-sm border shadow-black/5"
                                )}
                            >
                                {msg.content}
                            </div>
                        </div>
                    ))}
                    <div ref={messagesEndRef} />
                </div>

                {/* Input Area */}
                <div className="p-6 bg-gradient-to-t from-background via-background/95 to-transparent absolute bottom-0 w-full z-20">
                    <form onSubmit={handleSendMessage} className="max-w-3xl mx-auto flex gap-3 items-center">
                        <div className="relative flex-1 group">
                            <div className="absolute inset-0 bg-primary/20 blur-xl rounded-full opacity-0 group-focus-within:opacity-100 transition-opacity duration-500" />
                            <Input
                                value={inputValue}
                                onChange={e => setInputValue(e.target.value)}
                                placeholder="Type your response in Norwegian..."
                                className="pr-10 h-14 pl-6 rounded-full shadow-lg border-primary/20 bg-card/80 backdrop-blur text-lg focus-visible:ring-primary/50 relative z-10"
                                autoFocus
                            />
                            <Button
                                type="button"
                                size="icon"
                                variant="ghost"
                                className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-primary z-20 hover:bg-transparent"
                                title="Get Hint"
                            >
                                <Sparkles className="w-5 h-5" />
                            </Button>
                        </div>
                        <Button type="submit" size="icon" className="h-14 w-14 rounded-full shadow-lg shrink-0" disabled={!inputValue.trim()}>
                            <Send className="w-6 h-6 ml-0.5" />
                        </Button>
                    </form>
                </div>
            </div>

            <MissionReportModal
                open={showReport}
                onOpenChange={setShowReport}
                score={Math.round((completedKeywords.length / mission.keywords.length) * 100)}
                feedback="You did a great job using the required vocabulary. Try to focus more on sentence structure next time."
                onHome={() => navigate('/chat')}
                onRestart={() => window.location.reload()}
            />
        </div>
    )
}
