"use client"

import type React from "react"

import { useState } from "react"
import { Search, MapPin, Phone, Video, MoreVertical, Users, Navigation } 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, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import Link from "next/link"
import { useRouter } from "next/navigation"

// Mock user data
const mockUsers = [
  {
    id: "1",
    firstName: "Alice",
    lastName: "Johnson",
    email: "alice@example.com",
    avatar: "/diverse-woman-portrait.png",
    isOnline: true,
    lastSeen: new Date(),
    location: { lat: 40.7128, lng: -74.006, city: "New York", distance: 0.5 },
    bio: "Software developer passionate about tech",
    lastMessage: "That sounds exciting! I'd love to hear more about it.",
    lastMessageTime: new Date(Date.now() - 1000 * 60 * 45),
    unreadCount: 0,
  },
  {
    id: "2",
    firstName: "Bob",
    lastName: "Smith",
    email: "bob@example.com",
    avatar: "/thoughtful-man.png",
    isOnline: false,
    lastSeen: new Date(Date.now() - 1000 * 60 * 30), // 30 minutes ago
    location: { lat: 40.7589, lng: -73.9851, city: "New York", distance: 2.1 },
    bio: "Designer and coffee enthusiast",
    lastMessage: "Hey! How's your project going?",
    lastMessageTime: new Date(Date.now() - 1000 * 60 * 60 * 2),
    unreadCount: 2,
  },
  {
    id: "3",
    firstName: "Carol",
    lastName: "Davis",
    email: "carol@example.com",
    avatar: "/professional-woman.png",
    isOnline: true,
    lastSeen: new Date(),
    location: { lat: 40.7505, lng: -73.9934, city: "New York", distance: 1.8 },
    bio: "Marketing manager and travel lover",
    lastMessage: "Thanks for the recommendation!",
    lastMessageTime: new Date(Date.now() - 1000 * 60 * 60 * 5),
    unreadCount: 0,
  },
  {
    id: "4",
    firstName: "David",
    lastName: "Wilson",
    email: "david@example.com",
    avatar: "/man-with-detailed-beard.png",
    isOnline: false,
    lastSeen: new Date(Date.now() - 1000 * 60 * 60 * 2), // 2 hours ago
    location: { lat: 40.7282, lng: -74.0776, city: "New York", distance: 5.2 },
    bio: "Photographer and nature enthusiast",
    lastMessage: "Let's plan that photo shoot!",
    lastMessageTime: new Date(Date.now() - 1000 * 60 * 60 * 8),
    unreadCount: 1,
  },
]

export default function ChatPage() {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedTab, setSelectedTab] = useState("all")
  const [locationEnabled, setLocationEnabled] = useState(false)

  const filteredUsers = mockUsers.filter((user) => {
    const matchesSearch =
      user.firstName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.lastName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.bio.toLowerCase().includes(searchQuery.toLowerCase())

    if (selectedTab === "online") {
      return matchesSearch && user.isOnline
    }
    if (selectedTab === "nearby") {
      return matchesSearch && user.location.distance <= 3
    }
    return matchesSearch
  })

  const requestLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          console.log("Location:", position.coords)
          setLocationEnabled(true)
        },
        (error) => {
          console.error("Location error:", error)
        },
      )
    }
  }

  const openLocationServices = () => {
    router.push("/location")
  }

  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 formatMessageTime = (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))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

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

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

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

  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">
          <h1 className="text-2xl font-bold">Messages</h1>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="sm">
                <MoreVertical className="h-5 w-5" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={openLocationServices}>
                <Navigation className="h-4 w-4 mr-2" />
                Location Services
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => (window.location.href = "/profile")}>Profile Settings</DropdownMenuItem>
              <DropdownMenuItem onClick={() => (window.location.href = "/auth/signin")}>Sign Out</DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </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 conversations..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        {/* Location Toggle */}
        {!locationEnabled && (
          <Button variant="outline" size="sm" onClick={requestLocation} className="w-full mb-4 bg-transparent">
            <MapPin className="h-4 w-4 mr-2" />
            Enable Location for Nearby Search
          </Button>
        )}

        {/* Filter Tabs */}
        <Tabs value={selectedTab} onValueChange={setSelectedTab}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="all">All</TabsTrigger>
            <TabsTrigger value="online">Online</TabsTrigger>
            <TabsTrigger value="nearby" disabled={!locationEnabled}>
              Nearby
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {/* Conversation List */}
      <div className="p-4 space-y-2">
        {filteredUsers.length === 0 ? (
          <div className="text-center py-8">
            <Users className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">No conversations found</p>
          </div>
        ) : (
          filteredUsers.map((user) => (
            <Link key={user.id} href={`/chat/${user.id}`}>
              <Card className="hover:bg-accent/50 transition-colors cursor-pointer">
                <CardContent className="p-4">
                  <div className="flex items-center space-x-3">
                    <div className="relative">
                      <Avatar className="h-12 w-12">
                        <AvatarImage
                          src={user.avatar || "/placeholder.svg"}
                          alt={`${user.firstName} ${user.lastName}`}
                        />
                        <AvatarFallback>
                          {user.firstName[0]}
                          {user.lastName[0]}
                        </AvatarFallback>
                      </Avatar>
                      {user.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 justify-between">
                        <h3 className="font-semibold truncate">
                          {user.firstName} {user.lastName}
                        </h3>
                        <div className="flex items-center space-x-2">
                          <span className="text-xs text-muted-foreground">
                            {formatMessageTime(user.lastMessageTime)}
                          </span>
                          {user.unreadCount > 0 && (
                            <Badge variant="default" className="h-5 w-5 p-0 flex items-center justify-center text-xs">
                              {user.unreadCount}
                            </Badge>
                          )}
                        </div>
                      </div>
                      <p className="text-sm text-muted-foreground truncate">{user.lastMessage}</p>
                      <div className="flex items-center justify-between mt-1">
                        <span className="text-xs text-muted-foreground">
                          {user.isOnline ? "Online" : formatLastSeen(user.lastSeen)}
                        </span>
                        <div className="flex items-center space-x-1">
                          {locationEnabled && (
                            <Badge variant="secondary" className="text-xs">
                              <MapPin className="h-3 w-3 mr-1" />
                              {user.location.distance}km
                            </Badge>
                          )}
                          <Button variant="ghost" size="sm" onClick={(e) => handleVoiceCall(user.id, e)}>
                            <Phone className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={(e) => handleVideoCall(user.id, e)}>
                            <Video className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))
        )}
      </div>
    </div>
  )
}
