"use client"

import { useState, useEffect, useRef } from "react"
import Link from "next/link"
import { ChevronLeft, Send, Paperclip, MoreVertical } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { useAuth } from "@/components/auth-provider"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import useSWR from "swr"

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

interface Message {
  id: string
  senderId: string
  senderName: string
  senderAvatar?: string
  content: string
  timestamp: Date
  isSupport: boolean
}

export default function ChatPage() {
  const { user } = useAuth()
  const [message, setMessage] = useState("")
  const [messages, setMessages] = useState<Message[]>([])
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const [isTyping, setIsTyping] = useState(false)

  // Fetch existing chat messages
  const { data: chatData } = useSWR(user ? `/api/chat?userId=${user.id}` : null, fetcher, {
    refreshInterval: 5000, // Refresh every 5 seconds for real-time feel
  })

  useEffect(() => {
    if (chatData?.messages) {
      setMessages(chatData.messages)
    }
  }, [chatData])

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

  const handleSend = async () => {
    if (!message.trim() || !user) return

    const newMessage: Message = {
      id: Date.now().toString(),
      senderId: user.id,
      senderName: user.name,
      senderAvatar: user.avatar,
      content: message.trim(),
      timestamp: new Date(),
      isSupport: false,
    }

    setMessages((prev) => [...prev, newMessage])
    setMessage("")

    // Send to API
    try {
      await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userId: user.id,
          message: message.trim(),
        }),
      })

      // Simulate support typing
      setIsTyping(true)
      setTimeout(() => {
        setIsTyping(false)
        const supportResponse: Message = {
          id: (Date.now() + 1).toString(),
          senderId: "support",
          senderName: "Support",
          content: "Merci pour votre message. Un membre de notre équipe vous répondra bientôt.",
          timestamp: new Date(),
          isSupport: true,
        }
        setMessages((prev) => [...prev, supportResponse])
      }, 2000)
    } catch (error) {
      console.error("Failed to send message:", error)
    }
  }

  const formatTime = (date: Date) => {
    return new Date(date).toLocaleTimeString("fr-FR", {
      hour: "2-digit",
      minute: "2-digit",
    })
  }

  return (
    <div className="flex h-screen flex-col bg-background">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-border bg-secondary/50 px-4 py-3">
        <div className="flex items-center gap-3">
          <Link href="/settings" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <Avatar className="h-10 w-10">
            <AvatarImage src="/support-avatar.png" />
            <AvatarFallback>SA</AvatarFallback>
          </Avatar>
          <div>
            <h1 className="font-semibold text-foreground">Support Musique</h1>
            <div className="flex items-center gap-2">
              <span className="h-2 w-2 rounded-full bg-green-500"></span>
              <span className="text-xs text-muted-foreground">En ligne</span>
            </div>
          </div>
        </div>
        <button className="text-muted-foreground hover:text-primary">
          <MoreVertical className="h-5 w-5" />
        </button>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 pb-24">
        {messages.length === 0 ? (
          <div className="flex h-full flex-col items-center justify-center gap-4 text-center">
            <div className="rounded-full bg-secondary p-6">
              <Send className="h-8 w-8 text-muted-foreground" />
            </div>
            <div>
              <h2 className="mb-2 text-lg font-semibold text-foreground">Démarrer une conversation</h2>
              <p className="text-sm text-muted-foreground">
                Notre équipe de support est là pour vous aider
                <br />
                Posez-nous vos questions
              </p>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            {messages.map((msg) => (
              <div key={msg.id} className={`flex gap-3 ${msg.isSupport ? "justify-start" : "justify-end"}`}>
                {msg.isSupport && (
                  <Avatar className="h-8 w-8">
                    <AvatarImage src="/support-avatar.png" />
                    <AvatarFallback>SA</AvatarFallback>
                  </Avatar>
                )}
                <div
                  className={`max-w-[70%] rounded-2xl px-4 py-2 ${
                    msg.isSupport ? "bg-secondary text-foreground" : "bg-primary text-primary-foreground"
                  }`}
                >
                  <p className="text-sm">{msg.content}</p>
                  <span className="mt-1 block text-xs opacity-70">{formatTime(msg.timestamp)}</span>
                </div>
                {!msg.isSupport && (
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={msg.senderAvatar || "/placeholder.svg"} />
                    <AvatarFallback>{msg.senderName[0]}</AvatarFallback>
                  </Avatar>
                )}
              </div>
            ))}
            {isTyping && (
              <div className="flex gap-3">
                <Avatar className="h-8 w-8">
                  <AvatarImage src="/support-avatar.png" />
                  <AvatarFallback>SA</AvatarFallback>
                </Avatar>
                <div className="rounded-2xl bg-secondary px-4 py-3">
                  <div className="flex gap-1">
                    <span className="h-2 w-2 animate-bounce rounded-full bg-muted-foreground"></span>
                    <span className="h-2 w-2 animate-bounce rounded-full bg-muted-foreground delay-75"></span>
                    <span className="h-2 w-2 animate-bounce rounded-full bg-muted-foreground delay-150"></span>
                  </div>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>
        )}
      </div>

      {/* Input */}
      <div className="border-t border-border bg-background p-4">
        <div className="flex items-center gap-2">
          <button className="text-muted-foreground hover:text-primary">
            <Paperclip className="h-5 w-5" />
          </button>
          <input
            type="text"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyPress={(e) => e.key === "Enter" && handleSend()}
            placeholder="Écrivez votre message..."
            className="flex-1 rounded-full bg-secondary px-4 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <Button size="icon" onClick={handleSend} disabled={!message.trim()} className="rounded-full">
            <Send className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
