"use client"

import type React from "react"

import { useState, useEffect, useRef } from "react"
import { useParams, useRouter } from "next/navigation"
import { ArrowLeft, Send, Phone, Video, MoreVertical, Smile, Paperclip, Mic } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Card } from "@/components/ui/card"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"

interface Message {
  id: string
  senderId: string
  receiverId: string
  content: string
  timestamp: Date
  type: "text" | "image" | "file" | "audio"
  status: "sent" | "delivered" | "read"
}

interface User {
  id: string
  firstName: string
  lastName: string
  avatar?: string
  isOnline: boolean
  lastSeen: Date
}

// Mock data
const mockUsers: Record<string, User> = {
  "1": {
    id: "1",
    firstName: "Alice",
    lastName: "Johnson",
    avatar: "/diverse-woman-portrait.png",
    isOnline: true,
    lastSeen: new Date(),
  },
  "2": {
    id: "2",
    firstName: "Bob",
    lastName: "Smith",
    avatar: "/thoughtful-man.png",
    isOnline: false,
    lastSeen: new Date(Date.now() - 1000 * 60 * 30),
  },
}

const mockMessages: Message[] = [
  {
    id: "1",
    senderId: "1",
    receiverId: "current-user",
    content: "Hey! How are you doing?",
    timestamp: new Date(Date.now() - 1000 * 60 * 60),
    type: "text",
    status: "read",
  },
  {
    id: "2",
    senderId: "current-user",
    receiverId: "1",
    content: "I'm doing great! Just working on some new projects. How about you?",
    timestamp: new Date(Date.now() - 1000 * 60 * 50),
    type: "text",
    status: "read",
  },
  {
    id: "3",
    senderId: "1",
    receiverId: "current-user",
    content: "That sounds exciting! I'd love to hear more about it.",
    timestamp: new Date(Date.now() - 1000 * 60 * 45),
    type: "text",
    status: "read",
  },
  {
    id: "4",
    senderId: "current-user",
    receiverId: "1",
    content: "Let's catch up over a call sometime this week.",
    timestamp: new Date(Date.now() - 1000 * 60 * 30),
    type: "text",
    status: "delivered",
  },
]

export default function ChatConversationPage() {
  const params = useParams()
  const router = useRouter()
  const userId = params.userId as string
  const [messages, setMessages] = useState<Message[]>(mockMessages)
  const [newMessage, setNewMessage] = useState("")
  const [isTyping, setIsTyping] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)

  const currentUser = mockUsers[userId]

  useEffect(() => {
    // Scroll to bottom when messages change
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [messages])

  useEffect(() => {
    // Simulate real-time messaging
    const interval = setInterval(() => {
      if (Math.random() > 0.95) {
        // 5% chance every second to receive a message
        const newMsg: Message = {
          id: Date.now().toString(),
          senderId: userId,
          receiverId: "current-user",
          content: "This is a simulated real-time message!",
          timestamp: new Date(),
          type: "text",
          status: "delivered",
        }
        setMessages((prev) => [...prev, newMsg])
      }
    }, 1000)

    return () => clearInterval(interval)
  }, [userId])

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

    const message: Message = {
      id: Date.now().toString(),
      senderId: "current-user",
      receiverId: userId,
      content: newMessage,
      timestamp: new Date(),
      type: "text",
      status: "sent",
    }

    setMessages((prev) => [...prev, message])
    setNewMessage("")

    // Simulate message delivery
    setTimeout(() => {
      setMessages((prev) => prev.map((msg) => (msg.id === message.id ? { ...msg, status: "delivered" } : msg)))
    }, 1000)

    // Simulate message read
    setTimeout(() => {
      setMessages((prev) => prev.map((msg) => (msg.id === message.id ? { ...msg, status: "read" } : msg)))
    }, 3000)
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

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

  const formatLastSeen = (date: Date) => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))

    if (minutes < 1) return "Just now"
    if (minutes < 60) return `${minutes}m ago`
    if (hours < 24) return `${hours}h ago`
    return date.toLocaleDateString()
  }

  const handleVoiceCall = () => {
    console.log("[v0] Starting voice call with user:", userId)
    router.push(`/call/${userId}?type=audio`)
  }

  const handleVideoCall = () => {
    console.log("[v0] Starting video call with user:", userId)
    router.push(`/call/${userId}?type=video`)
  }

  if (!currentUser) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p>User not found</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-card border-b border-border p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Button variant="ghost" size="sm" onClick={() => router.back()}>
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <div className="relative">
              <Avatar className="h-10 w-10">
                <AvatarImage
                  src={currentUser.avatar || "/placeholder.svg"}
                  alt={`${currentUser.firstName} ${currentUser.lastName}`}
                />
                <AvatarFallback>
                  {currentUser.firstName[0]}
                  {currentUser.lastName[0]}
                </AvatarFallback>
              </Avatar>
              {currentUser.isOnline && (
                <div className="absolute -bottom-1 -right-1 h-3 w-3 bg-green-500 border-2 border-background rounded-full" />
              )}
            </div>
            <div>
              <h2 className="font-semibold">
                {currentUser.firstName} {currentUser.lastName}
              </h2>
              <p className="text-xs text-muted-foreground">
                {currentUser.isOnline ? "Online" : `Last seen ${formatLastSeen(currentUser.lastSeen)}`}
              </p>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="ghost" size="sm" onClick={handleVoiceCall}>
              <Phone className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="sm" onClick={handleVideoCall}>
              <Video className="h-4 w-4" />
            </Button>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm">
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem>View Profile</DropdownMenuItem>
                <DropdownMenuItem>Clear Chat</DropdownMenuItem>
                <DropdownMenuItem>Block User</DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((message, index) => {
          const isCurrentUser = message.senderId === "current-user"
          const showTimestamp =
            index === 0 || messages[index - 1].timestamp.getTime() - message.timestamp.getTime() > 5 * 60 * 1000

          return (
            <div key={message.id} className="space-y-2">
              {showTimestamp && (
                <div className="text-center">
                  <span className="text-xs text-muted-foreground bg-muted px-2 py-1 rounded-full">
                    {message.timestamp.toLocaleDateString()}
                  </span>
                </div>
              )}
              <div className={`flex ${isCurrentUser ? "justify-end" : "justify-start"}`}>
                <div className={`max-w-[70%] ${isCurrentUser ? "order-2" : "order-1"}`}>
                  <Card className={`p-3 ${isCurrentUser ? "bg-primary text-primary-foreground ml-auto" : "bg-muted"}`}>
                    <p className="text-sm">{message.content}</p>
                  </Card>
                  <div
                    className={`flex items-center mt-1 space-x-1 ${isCurrentUser ? "justify-end" : "justify-start"}`}
                  >
                    <span className="text-xs text-muted-foreground">{formatTime(message.timestamp)}</span>
                    {isCurrentUser && (
                      <div className="flex items-center">
                        {message.status === "sent" && <div className="h-2 w-2 bg-muted-foreground rounded-full" />}
                        {message.status === "delivered" && (
                          <div className="flex space-x-0.5">
                            <div className="h-2 w-2 bg-muted-foreground rounded-full" />
                            <div className="h-2 w-2 bg-muted-foreground rounded-full" />
                          </div>
                        )}
                        {message.status === "read" && (
                          <div className="flex space-x-0.5">
                            <div className="h-2 w-2 bg-primary rounded-full" />
                            <div className="h-2 w-2 bg-primary rounded-full" />
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )
        })}

        {isTyping && (
          <div className="flex justify-start">
            <div className="max-w-[70%]">
              <Card className="p-3 bg-muted">
                <div className="flex space-x-1">
                  <div className="h-2 w-2 bg-muted-foreground rounded-full animate-bounce" />
                  <div
                    className="h-2 w-2 bg-muted-foreground rounded-full animate-bounce"
                    style={{ animationDelay: "0.1s" }}
                  />
                  <div
                    className="h-2 w-2 bg-muted-foreground rounded-full animate-bounce"
                    style={{ animationDelay: "0.2s" }}
                  />
                </div>
              </Card>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* Message Input */}
      <div className="sticky bottom-0 bg-card border-t border-border p-4">
        <div className="flex items-center space-x-2">
          <Button variant="ghost" size="sm">
            <Paperclip className="h-4 w-4" />
          </Button>
          <div className="flex-1 relative">
            <Input
              placeholder="Type a message..."
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              className="pr-10"
            />
            <Button variant="ghost" size="sm" className="absolute right-1 top-1/2 transform -translate-y-1/2">
              <Smile className="h-4 w-4" />
            </Button>
          </div>
          {newMessage.trim() ? (
            <Button size="sm" onClick={handleSendMessage}>
              <Send className="h-4 w-4" />
            </Button>
          ) : (
            <Button variant="ghost" size="sm">
              <Mic className="h-4 w-4" />
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}
