"use client"

import { useState } from "react"
import { ArrowLeft, Search, UserPlus, Phone, Video, MessageCircle, MoreVertical } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { useRouter } from "next/navigation"

interface Contact {
  id: string
  firstName: string
  lastName: string
  email: string
  phone?: string
  avatar?: string
  isOnline: boolean
  lastSeen: Date
  isFavorite: boolean
}

const mockContacts: Contact[] = [
  {
    id: "1",
    firstName: "Alice",
    lastName: "Johnson",
    email: "alice@example.com",
    phone: "+1 (555) 123-4567",
    avatar: "/diverse-woman-portrait.png",
    isOnline: true,
    lastSeen: new Date(),
    isFavorite: true,
  },
  {
    id: "2",
    firstName: "Bob",
    lastName: "Smith",
    email: "bob@example.com",
    phone: "+1 (555) 234-5678",
    avatar: "/thoughtful-man.png",
    isOnline: false,
    lastSeen: new Date(Date.now() - 1000 * 60 * 30),
    isFavorite: false,
  },
  {
    id: "3",
    firstName: "Carol",
    lastName: "Davis",
    email: "carol@example.com",
    phone: "+1 (555) 345-6789",
    avatar: "/professional-woman.png",
    isOnline: true,
    lastSeen: new Date(),
    isFavorite: true,
  },
  {
    id: "4",
    firstName: "David",
    lastName: "Wilson",
    email: "david@example.com",
    phone: "+1 (555) 456-7890",
    avatar: "/man-with-detailed-beard.png",
    isOnline: false,
    lastSeen: new Date(Date.now() - 1000 * 60 * 60 * 2),
    isFavorite: false,
  },
]

export default function ContactsPage() {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false)

  const filteredContacts = mockContacts.filter((contact) => {
    const matchesSearch =
      contact.firstName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      contact.lastName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      contact.email.toLowerCase().includes(searchQuery.toLowerCase())

    if (showFavoritesOnly) {
      return matchesSearch && contact.isFavorite
    }
    return matchesSearch
  })

  const favoriteContacts = filteredContacts.filter((contact) => contact.isFavorite)
  const regularContacts = filteredContacts.filter((contact) => !contact.isFavorite)

  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 handleMessage = (contactId: string) => {
    router.push(`/chat/${contactId}`)
  }

  const handleCall = (contactId: string, type: "audio" | "video") => {
    console.log(`[v0] Starting ${type} call with contact:`, contactId)
    router.push(`/call/${contactId}?type=${type}`)
  }

  const ContactCard = ({ contact }: { contact: Contact }) => (
    <Card className="hover:bg-accent/50 transition-colors">
      <CardContent className="p-4">
        <div className="flex items-center space-x-3">
          <div className="relative">
            <Avatar className="h-12 w-12">
              <AvatarImage
                src={contact.avatar || "/placeholder.svg"}
                alt={`${contact.firstName} ${contact.lastName}`}
              />
              <AvatarFallback>
                {contact.firstName[0]}
                {contact.lastName[0]}
              </AvatarFallback>
            </Avatar>
            {contact.isOnline && (
              <div className="absolute -bottom-1 -right-1 h-4 w-4 bg-green-500 border-2 border-background rounded-full" />
            )}
          </div>

          <div className="flex-1 min-w-0">
            <div className="flex items-center space-x-2">
              <h3 className="font-semibold truncate">
                {contact.firstName} {contact.lastName}
              </h3>
              {contact.isFavorite && <Badge variant="secondary">★</Badge>}
            </div>
            <p className="text-sm text-muted-foreground truncate">{contact.email}</p>
            <p className="text-xs text-muted-foreground">
              {contact.isOnline ? "Online" : `Last seen ${formatLastSeen(contact.lastSeen)}`}
            </p>
          </div>

          <div className="flex items-center space-x-1">
            <Button variant="ghost" size="sm" onClick={() => handleMessage(contact.id)}>
              <MessageCircle className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="sm" onClick={() => handleCall(contact.id, "audio")}>
              <Phone className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="sm" onClick={() => handleCall(contact.id, "video")}>
              <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>{contact.isFavorite ? "Remove from Favorites" : "Add to Favorites"}</DropdownMenuItem>
                <DropdownMenuItem>Block Contact</DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </CardContent>
    </Card>
  )

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-card border-b border-border p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-3">
            <Button variant="ghost" size="sm" onClick={() => router.back()}>
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <div>
              <h1 className="text-xl font-semibold">Contacts</h1>
              <p className="text-sm text-muted-foreground">{filteredContacts.length} contacts</p>
            </div>
          </div>
          <Button variant="outline" size="sm">
            <UserPlus className="h-4 w-4 mr-1" />
            Add Contact
          </Button>
        </div>

        {/* Search Bar */}
        <div className="relative mb-4">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search contacts..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        {/* Filter Toggle */}
        <div className="flex items-center space-x-2">
          <Button
            variant={showFavoritesOnly ? "default" : "outline"}
            size="sm"
            onClick={() => setShowFavoritesOnly(!showFavoritesOnly)}
          >
            ★ Favorites Only
          </Button>
        </div>
      </div>

      <div className="p-4 space-y-6">
        {/* Favorites Section */}
        {!showFavoritesOnly && favoriteContacts.length > 0 && (
          <div>
            <h2 className="text-lg font-semibold mb-3 flex items-center space-x-2">
              <span>Favorites</span>
              <Badge variant="secondary">{favoriteContacts.length}</Badge>
            </h2>
            <div className="space-y-2">
              {favoriteContacts.map((contact) => (
                <ContactCard key={contact.id} contact={contact} />
              ))}
            </div>
          </div>
        )}

        {/* All Contacts Section */}
        <div>
          {!showFavoritesOnly && (
            <h2 className="text-lg font-semibold mb-3 flex items-center space-x-2">
              <span>All Contacts</span>
              <Badge variant="secondary">{regularContacts.length}</Badge>
            </h2>
          )}

          {filteredContacts.length === 0 ? (
            <div className="text-center py-8">
              <UserPlus className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">No contacts found</p>
            </div>
          ) : (
            <div className="space-y-2">
              {(showFavoritesOnly ? favoriteContacts : regularContacts).map((contact) => (
                <ContactCard key={contact.id} contact={contact} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
