"use client"

import type React from "react"

import { useState } from "react"
import {
  MessageCircle,
  Phone,
  Users,
  MapPin,
  Settings,
  Search,
  Bell,
  ShoppingBag,
  TrendingUp,
  Megaphone,
  Plus,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } 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 Link from "next/link"
import { useRouter } from "next/navigation"

interface QuickAction {
  id: string
  title: string
  description: string
  icon: React.ReactNode
  href: string
  color: string
}

interface RecentActivity {
  id: string
  type: "message" | "call" | "location" | "marketplace" | "ad"
  user: {
    id: string
    name: string
    avatar?: string
  }
  content: string
  timestamp: Date
  unread?: boolean
}

const quickActions: QuickAction[] = [
  {
    id: "messages",
    title: "Messages",
    description: "Chat with friends",
    icon: <MessageCircle className="h-6 w-6" />,
    href: "/chat",
    color: "bg-blue-500",
  },
  {
    id: "calls",
    title: "Calls",
    description: "Voice & video calls",
    icon: <Phone className="h-6 w-6" />,
    href: "/calls",
    color: "bg-green-500",
  },
  {
    id: "ads",
    title: "Advertisements",
    description: "Post & browse ads",
    icon: <Megaphone className="h-6 w-6" />,
    href: "/ads",
    color: "bg-purple-500",
  },
  {
    id: "marketplace",
    title: "Marketplace",
    description: "Buy & sell items",
    icon: <ShoppingBag className="h-6 w-6" />,
    href: "/marketplace",
    color: "bg-amber-500",
  },
  {
    id: "nearby",
    title: "Nearby",
    description: "Find people around you",
    icon: <MapPin className="h-6 w-6" />,
    href: "/location",
    color: "bg-orange-500",
  },
]

const mockRecentActivity: RecentActivity[] = [
  {
    id: "1",
    type: "message",
    user: { id: "1", name: "Alice Johnson", avatar: "/diverse-woman-portrait.png" },
    content: "That sounds exciting! I'd love to hear more about it.",
    timestamp: new Date(Date.now() - 1000 * 60 * 15),
    unread: true,
  },
  {
    id: "2",
    type: "ad",
    user: { id: "2", name: "Alex Chen", avatar: "/professional-man.png" },
    content: "Interested in your web development services ad",
    timestamp: new Date(Date.now() - 1000 * 60 * 20),
    unread: true,
  },
  {
    id: "3",
    type: "marketplace",
    user: { id: "3", name: "Sarah Chen", avatar: "/professional-woman.png" },
    content: "Interested in your iPhone 14 Pro Max listing",
    timestamp: new Date(Date.now() - 1000 * 60 * 30),
    unread: true,
  },
  {
    id: "4",
    type: "call",
    user: { id: "4", name: "Bob Smith", avatar: "/thoughtful-man.png" },
    content: "Missed video call",
    timestamp: new Date(Date.now() - 1000 * 60 * 45),
  },
  {
    id: "5",
    type: "message",
    user: { id: "5", name: "Carol Davis", avatar: "/professional-woman.png" },
    content: "Thanks for the recommendation!",
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2),
  },
  {
    id: "6",
    type: "location",
    user: { id: "6", name: "David Wilson", avatar: "/man-with-detailed-beard.png" },
    content: "Shared location with you",
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 3),
  },
]

export default function DashboardPage() {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")
  const [notifications, setNotifications] = useState(5) // Updated notification count to include ads
  const [onlineUsers, setOnlineUsers] = useState(12)
  const [activeListings, setActiveListings] = useState(2)
  const [activeAds, setActiveAds] = useState(1) // Added active ads count

  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))

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

  const getActivityIcon = (type: string) => {
    switch (type) {
      case "message":
        return <MessageCircle className="h-4 w-4" />
      case "call":
        return <Phone className="h-4 w-4" />
      case "location":
        return <MapPin className="h-4 w-4" />
      case "marketplace":
        return <ShoppingBag className="h-4 w-4" />
      case "ad":
        return <Megaphone className="h-4 w-4" />
      default:
        return <MessageCircle className="h-4 w-4" />
    }
  }

  return (
    <div className="min-h-screen bg-background pb-20">
      {/* 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>
            <h1 className="text-2xl font-bold">Dashboard</h1>
            <p className="text-sm text-muted-foreground">Welcome back! You have {notifications} new notifications</p>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="ghost" size="sm" className="relative">
              <Bell className="h-5 w-5" />
              {notifications > 0 && (
                <Badge className="absolute -top-1 -right-1 h-5 w-5 p-0 flex items-center justify-center text-xs">
                  {notifications}
                </Badge>
              )}
            </Button>
            <Button variant="ghost" size="sm" onClick={() => router.push("/profile")}>
              <Settings className="h-5 w-5" />
            </Button>
          </div>
        </div>

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

      <div className="p-4 space-y-6">
        {/* Stats Cards */}
        <div className="grid grid-cols-4 gap-3">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center space-x-2">
                <div className="p-2 bg-green-100 rounded-full">
                  <Users className="h-4 w-4 text-green-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Online</p>
                  <p className="text-lg font-bold">{onlineUsers}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center space-x-2">
                <div className="p-2 bg-blue-100 rounded-full">
                  <MessageCircle className="h-4 w-4 text-blue-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Messages</p>
                  <p className="text-lg font-bold">3</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center space-x-2">
                <div className="p-2 bg-purple-100 rounded-full">
                  <Megaphone className="h-4 w-4 text-purple-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">My Ads</p>
                  <p className="text-lg font-bold">{activeAds}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center space-x-2">
                <div className="p-2 bg-amber-100 rounded-full">
                  <TrendingUp className="h-4 w-4 text-amber-600" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Listings</p>
                  <p className="text-lg font-bold">{activeListings}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        <div className="flex gap-2">
          <Link href="/ads/post" className="flex-1">
            <Button className="w-full bg-purple-600 hover:bg-purple-700">
              <Plus className="w-4 h-4 mr-2" />
              Post Advertisement
            </Button>
          </Link>
          <Link href="/marketplace/sell" className="flex-1">
            <Button variant="outline" className="w-full bg-transparent">
              <Plus className="w-4 h-4 mr-2" />
              Sell Item
            </Button>
          </Link>
        </div>

        {/* Quick Actions */}
        <Card>
          <CardHeader>
            <CardTitle>Quick Actions</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4">
              {quickActions.map((action) => (
                <Link key={action.id} href={action.href}>
                  <Card className="hover:bg-accent/50 transition-colors cursor-pointer">
                    <CardContent className="p-4">
                      <div className="flex items-center space-x-3">
                        <div className={`p-3 rounded-full text-white ${action.color}`}>{action.icon}</div>
                        <div>
                          <p className="font-medium">{action.title}</p>
                          <p className="text-sm text-muted-foreground">{action.description}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Recent Activity */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle>Recent Activity</CardTitle>
              <Button variant="ghost" size="sm" onClick={() => router.push("/chat")}>
                View All
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {mockRecentActivity.map((activity) => (
                <div
                  key={activity.id}
                  className={`flex items-center space-x-3 p-3 rounded-lg border cursor-pointer hover:bg-accent/50 transition-colors ${
                    activity.unread ? "bg-primary/5 border-primary/20" : ""
                  }`}
                  onClick={() => {
                    if (activity.type === "marketplace") {
                      router.push("/marketplace")
                    } else if (activity.type === "ad") {
                      router.push("/ads")
                    } else {
                      router.push(`/chat/${activity.user.id}`)
                    }
                  }}
                >
                  <Avatar className="h-10 w-10">
                    <AvatarImage src={activity.user.avatar || "/placeholder.svg"} alt={activity.user.name} />
                    <AvatarFallback>{activity.user.name[0]}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-2">
                      <p className="font-medium truncate">{activity.user.name}</p>
                      <div className="text-muted-foreground">{getActivityIcon(activity.type)}</div>
                      {activity.unread && <div className="h-2 w-2 bg-primary rounded-full" />}
                    </div>
                    <p className="text-sm text-muted-foreground truncate">{activity.content}</p>
                  </div>
                  <span className="text-xs text-muted-foreground">{formatTime(activity.timestamp)}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Status Card */}
        <Card>
          <CardHeader>
            <CardTitle>Your Status</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-3">
                <Avatar className="h-12 w-12">
                  <AvatarImage src="/professional-man.png" alt="You" />
                  <AvatarFallback>You</AvatarFallback>
                </Avatar>
                <div>
                  <p className="font-medium">John Doe</p>
                  <div className="flex items-center space-x-2">
                    <div className="h-2 w-2 bg-green-500 rounded-full" />
                    <span className="text-sm text-muted-foreground">Online</span>
                  </div>
                </div>
              </div>
              <Button variant="outline" size="sm" onClick={() => router.push("/profile")}>
                Edit Profile
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
