"use client"

import { useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Send, Paperclip } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { BottomNav } from "@/components/bottom-nav"
import { useUser } from "@/components/user-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"
import { formatDistanceToNow } from "date-fns"
import { fr } from "date-fns/locale"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

export default function TicketDetailPage() {
  const params = useParams()
  const { user } = useUser()
  const { toast } = useToast()
  const { data, mutate } = useSWR(`/api/support/${params.id}`, fetcher)

  const [message, setMessage] = useState("")
  const [isSending, setIsSending] = useState(false)

  const ticket = data?.ticket
  const messages = data?.messages || []

  const handleSendMessage = async () => {
    if (!message.trim() || !user?.id) return

    setIsSending(true)
    try {
      const res = await fetch(`/api/support/${params.id}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: user.id, message }),
      })

      if (res.ok) {
        setMessage("")
        mutate()
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible d'envoyer le message", variant: "destructive" })
    } finally {
      setIsSending(false)
    }
  }

  if (!ticket) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <p className="text-muted-foreground">Chargement...</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background pb-24 flex flex-col">
      <div className="mx-auto w-full max-w-2xl px-4 py-6 flex-1 flex flex-col">
        {/* Header */}
        <div className="mb-6 flex items-center gap-4">
          <Link href="/support" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <div className="flex-1">
            <h1 className="text-xl font-bold text-foreground">{ticket.subject}</h1>
            <p className="text-sm text-muted-foreground">Ticket #{ticket.id.slice(0, 8)}</p>
          </div>
          <Badge className="bg-blue-500/20 text-blue-400 border-0">{ticket.status}</Badge>
        </div>

        {/* Messages */}
        <div className="flex-1 space-y-4 overflow-auto mb-4">
          {messages.map((msg: any) => (
            <div key={msg.id} className={`flex gap-3 ${msg.is_staff_reply ? "flex-row-reverse" : ""}`}>
              <Avatar className="w-8 h-8 flex-shrink-0">
                <AvatarImage src={msg.avatar_url || "/placeholder.svg"} />
                <AvatarFallback>{msg.user_name?.[0] || "?"}</AvatarFallback>
              </Avatar>
              <div className={`flex-1 ${msg.is_staff_reply ? "flex flex-col items-end" : ""}`}>
                <div className="flex items-baseline gap-2 mb-1">
                  <span className="text-sm font-medium text-foreground">{msg.user_name}</span>
                  {msg.is_staff_reply && (
                    <Badge className="bg-purple-500/20 text-purple-400 border-0 text-xs">Support</Badge>
                  )}
                </div>
                <div
                  className={`p-3 rounded-xl ${
                    msg.is_staff_reply ? "bg-purple-500/20 text-white" : "bg-secondary/50 text-foreground"
                  }`}
                >
                  <p className="text-sm">{msg.message}</p>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  {formatDistanceToNow(new Date(msg.created_at), {
                    addSuffix: true,
                    locale: fr,
                  })}
                </p>
              </div>
            </div>
          ))}
        </div>

        {/* Reply Input */}
        <div className="border-t border-secondary/50 pt-4">
          <div className="flex gap-2">
            <Button variant="ghost" size="icon" className="text-muted-foreground">
              <Paperclip className="w-5 h-5" />
            </Button>
            <Textarea
              placeholder="Votre réponse..."
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              className="bg-secondary/50 border-secondary text-foreground resize-none"
              rows={2}
            />
            <Button
              onClick={handleSendMessage}
              disabled={isSending || !message.trim()}
              className="bg-purple-600 hover:bg-purple-700"
            >
              <Send className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
