"use client"

import { useState } from "react"
import { ArrowLeft, Phone, Video, PhoneCall, PhoneIncoming, PhoneMissed, Clock, Search } 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 { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { useRouter } from "next/navigation"

interface CallRecord {
  id: string
  user: {
    id: string
    firstName: string
    lastName: string
    avatar?: string
  }
  type: "incoming" | "outgoing" | "missed"
  callType: "audio" | "video"
  timestamp: Date
  duration?: number // in seconds
}

const mockCallHistory: CallRecord[] = [
  {
    id: "1",
    user: { id: "1", firstName: "Alice", lastName: "Johnson", avatar: "/diverse-woman-portrait.png" },
    type: "outgoing",
    callType: "video",
    timestamp: new Date(Date.now() - 1000 * 60 * 30),
    duration: 1245, // 20:45
  },
  {
    id: "2",
    user: { id: "2", firstName: "Bob", lastName: "Smith", avatar: "/thoughtful-man.png" },
    type: "missed",
    callType: "audio",
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2),
  },
  {
    id: "3",
    user: { id: "3", firstName: "Carol", lastName: "Davis", avatar: "/professional-woman.png" },
    type: "incoming",
    callType: "video",
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 4),
    duration: 892, // 14:52
  },
  {
    id: "4",
    user: { id: "4", firstName: "David", lastName: "Wilson", avatar: "/man-with-detailed-beard.png" },
    type: "outgoing",
    callType: "audio",
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 8),
    duration: 567, // 9:27
  },
]

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

  const filteredCalls = mockCallHistory.filter((call) => {
    const matchesSearch =
      call.user.firstName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      call.user.lastName.toLowerCase().includes(searchQuery.toLowerCase())

    if (selectedTab === "missed") {
      return matchesSearch && call.type === "missed"
    }
    if (selectedTab === "outgoing") {
      return matchesSearch && call.type === "outgoing"
    }
    if (selectedTab === "incoming") {
      return matchesSearch && call.type === "incoming"
    }
    return matchesSearch
  })

  const formatTime = (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 "Just now"
    if (minutes < 60) return `${minutes}m ago`
    if (hours < 24) return `${hours}h ago`
    if (days < 7) return `${days}d ago`
    return date.toLocaleDateString()
  }

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, "0")}`
  }

  const getCallIcon = (type: string, callType: string) => {
    if (type === "missed") {
      return <PhoneMissed className="h-4 w-4 text-red-500" />
    }
    if (type === "incoming") {
      return <PhoneIncoming className="h-4 w-4 text-green-500" />
    }
    if (callType === "video") {
      return <Video className="h-4 w-4 text-blue-500" />
    }
    return <PhoneCall className="h-4 w-4 text-blue-500" />
  }

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

  const missedCallsCount = mockCallHistory.filter((call) => call.type === "missed").length

  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">Calls</h1>
              {missedCallsCount > 0 && <p className="text-sm text-muted-foreground">{missedCallsCount} missed calls</p>}
            </div>
          </div>
        </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 call history..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        {/* Filter Tabs */}
        <Tabs value={selectedTab} onValueChange={setSelectedTab}>
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="all">All</TabsTrigger>
            <TabsTrigger value="missed">
              Missed
              {missedCallsCount > 0 && (
                <Badge variant="destructive" className="ml-1 h-4 w-4 p-0 text-xs">
                  {missedCallsCount}
                </Badge>
              )}
            </TabsTrigger>
            <TabsTrigger value="outgoing">Outgoing</TabsTrigger>
            <TabsTrigger value="incoming">Incoming</TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {/* Call History */}
      <div className="p-4">
        {filteredCalls.length === 0 ? (
          <div className="text-center py-8">
            <Phone className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">No calls found</p>
          </div>
        ) : (
          <div className="space-y-2">
            {filteredCalls.map((call) => (
              <Card key={call.id} className="hover:bg-accent/50 transition-colors">
                <CardContent className="p-4">
                  <div className="flex items-center space-x-3">
                    <Avatar className="h-12 w-12">
                      <AvatarImage
                        src={call.user.avatar || "/placeholder.svg"}
                        alt={`${call.user.firstName} ${call.user.lastName}`}
                      />
                      <AvatarFallback>
                        {call.user.firstName[0]}
                        {call.user.lastName[0]}
                      </AvatarFallback>
                    </Avatar>

                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2">
                        <h3 className="font-semibold truncate">
                          {call.user.firstName} {call.user.lastName}
                        </h3>
                        {getCallIcon(call.type, call.callType)}
                      </div>
                      <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                        <span>{formatTime(call.timestamp)}</span>
                        {call.duration && (
                          <>
                            <span>•</span>
                            <div className="flex items-center space-x-1">
                              <Clock className="h-3 w-3" />
                              <span>{formatDuration(call.duration)}</span>
                            </div>
                          </>
                        )}
                      </div>
                    </div>

                    <div className="flex items-center space-x-1">
                      <Button variant="ghost" size="sm" onClick={() => handleCall(call.user.id, "audio")}>
                        <Phone className="h-4 w-4" />
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => handleCall(call.user.id, "video")}>
                        <Video className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
