"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { Ticket, TicketMessage, ticketsApi } from "@/lib/api"
import { toast } from "sonner"
import { Send, ArrowLeft } from "lucide-react"
import { formatDistanceToNow } from "date-fns"

export default function TicketDetailsPage() {
    const params = useParams()
    const router = useRouter()
    const ticketId = params.id as string

    const [ticket, setTicket] = useState<Ticket | null>(null)
    const [messages, setMessages] = useState<TicketMessage[]>([])
    const [loading, setLoading] = useState(true)
    const [inputText, setInputText] = useState("")

    const fetchTicket = async () => {
        try {
            const data = await ticketsApi.get(ticketId)
            setTicket(data.ticket)
            setMessages(data.messages)
            setLoading(false)
        } catch (error) {
            console.error("Failed to load ticket", error)
            toast.error("Failed to load ticket")
            setLoading(false)
        }
    }

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

    const handleSendMessage = async () => {
        if (!inputText.trim()) return

        try {
            const newMsg = await ticketsApi.sendMessage(ticketId, inputText)
            setMessages([...messages, newMsg])
            setInputText("")
        } catch (error) {
            console.error("Failed to send message", error)
            toast.error("Failed to send message")
        }
    }

    if (loading) {
        return <div className="p-8 text-center text-muted-foreground">Loading ticket details...</div>
    }

    if (!ticket) {
        return <div className="p-8 text-center text-destructive">Ticket not found</div>
    }

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center gap-4">
                <Button variant="outline" size="icon" onClick={() => router.back()}>
                    <ArrowLeft className="h-4 w-4" />
                </Button>
                <div>
                    <h1 className="text-2xl font-bold flex items-center gap-2">
                        Ticket #{ticket.id.substring(0, 8)}
                        <Badge variant={ticket.status === 'open' ? 'default' : 'outline'}>{ticket.status}</Badge>
                    </h1>
                    <h2 className="text-lg text-muted-foreground">{ticket.subject}</h2>
                </div>
            </div>

            <div className="grid grid-cols-3 gap-6">
                {/* Main Chat Area */}
                <Card className="col-span-2 h-[600px] flex flex-col">
                    <CardHeader className="border-b">
                        <CardTitle>Conversation</CardTitle>
                    </CardHeader>
                    <ScrollArea className="flex-1 p-4">
                        <div className="space-y-4">
                            {messages.map((msg) => {
                                // Simple logic: if message userId matches ticket.userId, it's user. Else support/admin.
                                // Actually, we don't know current User ID here easily without context.
                                // But typically, 'me' is on right.
                                // For now, let's align all to left/right based on logic if we can.
                                // If `ticketsApi.get` returns `isSupport` flag? No.
                                // We will just stack them.
                                return (
                                    <div key={msg.id} className="bg-muted p-3 rounded-lg max-w-[80%]">
                                        <p className="text-sm">{msg.message}</p>
                                        <span className="text-xs text-muted-foreground mt-1 block">
                                            {formatDistanceToNow(new Date(msg.createdAt))} ago
                                        </span>
                                    </div>
                                )
                            })}
                        </div>
                    </ScrollArea>
                    <div className="p-4 border-t flex gap-2">
                        <Input
                            value={inputText}
                            onChange={(e) => setInputText(e.target.value)}
                            placeholder="Type a reply..."
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') handleSendMessage()
                            }}
                        />
                        <Button onClick={handleSendMessage}>
                            <Send className="h-4 w-4" />
                        </Button>
                    </div>
                </Card>

                {/* Sidebar / Meta */}
                <Card className="h-fit">
                    <CardHeader>
                        <CardTitle>Details</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div>
                            <span className="text-sm font-medium text-muted-foreground">Priority</span>
                            <p className="capitalize">{ticket.priority}</p>
                        </div>
                        <div>
                            <span className="text-sm font-medium text-muted-foreground">Created</span>
                            <p>{new Date(ticket.createdAt).toLocaleDateString()}</p>
                        </div>
                        <div>
                            <span className="text-sm font-medium text-muted-foreground">Status</span>
                            <p className="capitalize">{ticket.status}</p>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    )
}
