"use client"

import { useEffect, useState, useRef } from "react"
import { useParams, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { ArrowLeft, Send } from "lucide-react"
import { ticketsApi, type Ticket, type TicketMessage } from "@/lib/api"
import { toast } from "sonner"
import { getCurrentUser } from "@/lib/auth"

export default function TicketDetailsPage() {
    const params = useParams()
    const router = useRouter()
    const id = params.id as string
    const [ticket, setTicket] = useState<Ticket | null>(null)
    const [messages, setMessages] = useState<TicketMessage[]>([])
    const [newMessage, setNewMessage] = useState("")
    const [loading, setLoading] = useState(true)
    const messagesEndRef = useRef<HTMLDivElement>(null)

    // Simple user check
    const currentUser = getCurrentUser()
    const currentUserId = currentUser?.id ? parseInt(currentUser.id) : 0 // Assuming ID is accessible

    const fetchTicket = async () => {
        try {
            const data = await ticketsApi.get(id)
            setTicket(data.ticket)
            setMessages(data.messages || [])
        } catch (error) {
            toast.error("Failed to load ticket")
            router.push("/dashboard/support/tickets")
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        if (id) fetchTicket()
    }, [id])

    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
    }, [messages])

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

        try {
            const msg = await ticketsApi.sendMessage(id, newMessage)
            setMessages([...messages, msg])
            setNewMessage("")
        } catch (error) {
            toast.error("Failed to send message")
        }
    }

    if (loading) return <div className="p-8 text-center">Loading ticket...</div>
    if (!ticket) return <div className="p-8 text-center">Ticket not found</div>

    return (
        <div className="flex flex-col h-[calc(100vh-8rem)]">
            <div className="flex items-center gap-4 mb-4">
                <Button variant="ghost" onClick={() => router.push("/dashboard/support/tickets")}>
                    <ArrowLeft className="mr-2 h-4 w-4" /> Back
                </Button>
                <div>
                    <h2 className="text-xl font-bold flex items-center gap-2">
                        {ticket.subject}
                        <Badge variant={ticket.status === 'open' ? 'default' : 'secondary'}>
                            {ticket.status}
                        </Badge>
                    </h2>
                    <p className="text-sm text-muted-foreground">ID: {ticket.id}</p>
                </div>
            </div>

            <Card className="flex-1 flex flex-col overflow-hidden">
                <CardHeader className="border-b py-3">
                    <CardTitle className="text-base font-medium">Chat History</CardTitle>
                </CardHeader>
                <CardContent className="flex-1 overflow-y-auto p-4 space-y-4 bg-muted/5">
                    {messages.length === 0 ? (
                        <div className="text-center text-muted-foreground py-8">No messages yet.</div>
                    ) : (
                        messages.map((msg) => {
                            // Determine if message is from current user
                            // We might need to check userId match.
                            // For now assuming we are sending if DB userId matches.
                            // But wait, `getCurrentUser` returns partial user. We assume ID is string there.
                            // DB uses Int.
                            // Let's assume right alignment for self.
                            // Actually, if we implemented this fully, we'd check properly.
                            // Let's just align right for now for testing.
                            const isMe = true; // TODO: Fix check
                            return (
                                <div key={msg.id} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                                    <div className={`max-w-[80%] rounded-lg p-3 ${isMe ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>
                                        <p className="text-sm">{msg.message}</p>
                                        <p className="text-[10px] opacity-70 mt-1 text-right">
                                            {new Date(msg.createdAt).toLocaleTimeString()}
                                        </p>
                                    </div>
                                </div>
                            )
                        })
                    )}
                    <div ref={messagesEndRef} />
                </CardContent>
                <CardFooter className="p-3 border-t">
                    <form onSubmit={handleSendMessage} className="flex w-full gap-2">
                        <Input
                            placeholder="Type your message..."
                            value={newMessage}
                            onChange={(e) => setNewMessage(e.target.value)}
                        />
                        <Button type="submit" size="icon">
                            <Send className="h-4 w-4" />
                        </Button>
                    </form>
                </CardFooter>
            </Card>
        </div>
    )
}
