"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, Trash2 } from "lucide-react"
import { formatDistanceToNow } from "date-fns"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"

export default function AdminTicketDetailsPage() {
    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 [deleteOpen, setDeleteOpen] = useState(false)

    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")
        }
    }

    const handleStatusChange = async (status: string) => {
        try {
            await ticketsApi.update(ticketId, { status })
            setTicket(prev => prev ? { ...prev, status: status as any } : null)
            toast.success("Status updated")
        } catch (error) {
            toast.error("Failed to update status")
        }
    }

    const handlePriorityChange = async (priority: string) => {
        try {
            await ticketsApi.update(ticketId, { priority })
            setTicket(prev => prev ? { ...prev, priority: priority as any } : null)
            toast.success("Priority updated")
        } catch (error) {
            toast.error("Failed to update priority")
        }
    }

    const handleDelete = async () => {
        try {
            await ticketsApi.delete(ticketId)
            toast.success("Ticket deleted")
            router.push("/dashboard/tickets")
        } catch (error) {
            toast.error("Failed to delete ticket")
        }
    }

    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 justify-between">
                <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>
                <Button variant="destructive" onClick={() => setDeleteOpen(true)}>
                    <Trash2 className="h-4 w-4 mr-2" />
                    Delete Ticket
                </Button>
            </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) => {
                                const isUser = msg.userId.toString() === ticket.userId.toString() // Assuming simple string match
                                return (
                                    <div key={msg.id} className={`flex ${isUser ? 'justify-start' : 'justify-end'}`}>
                                        <div className={`p-3 rounded-lg max-w-[80%] ${isUser ? 'bg-muted' : 'bg-primary text-primary-foreground'}`}>
                                            <p className="text-sm">{msg.message}</p>
                                            <span className={`text-xs mt-1 block ${isUser ? 'text-muted-foreground' : 'text-primary-foreground/80'}`}>
                                                {isUser ? 'User' : 'Admin'} • {formatDistanceToNow(new Date(msg.createdAt))} ago
                                            </span>
                                        </div>
                                    </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>Admin Controls</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div>
                            <span className="text-sm font-medium text-muted-foreground mb-2 block">Status</span>
                            <Select value={ticket.status} onValueChange={handleStatusChange}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="open">Open</SelectItem>
                                    <SelectItem value="in_progress">In Progress</SelectItem>
                                    <SelectItem value="closed">Closed</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div>
                            <span className="text-sm font-medium text-muted-foreground mb-2 block">Priority</span>
                            <Select value={ticket.priority} onValueChange={handlePriorityChange}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="low">Low</SelectItem>
                                    <SelectItem value="medium">Medium</SelectItem>
                                    <SelectItem value="high">High</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div>
                            <span className="text-sm font-medium text-muted-foreground">User ID</span>
                            <p className="font-mono text-xs mt-1 break-all bg-muted p-2 rounded">{ticket.userId}</p>
                        </div>
                        <div>
                            <span className="text-sm font-medium text-muted-foreground">Created</span>
                            <p className="mt-1">{new Date(ticket.createdAt).toLocaleString()}</p>
                        </div>
                    </CardContent>
                </Card>
            </div>

            <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Delete Ticket</DialogTitle>
                        <DialogDescription>
                            Are you sure? This will delete the ticket and all messages permanently.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setDeleteOpen(false)}>Cancel</Button>
                        <Button variant="destructive" onClick={handleDelete}>Delete</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
