"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Heart, Search, MapPin, Clock, Star, MessageCircle, Phone, Plus } from "lucide-react"
import Link from "next/link"

interface Advertisement {
  id: string
  title: string
  description: string
  type: "product" | "service"
  category: string
  price: number
  location: string
  postedAt: string
  images: string[]
  seller: {
    id: string
    name: string
    avatar: string
    rating: number
    verified: boolean
  }
  featured: boolean
  urgent: boolean
}

const mockAds: Advertisement[] = [
  {
    id: "1",
    title: "Professional Web Development Services",
    description: "Full-stack web development with React, Node.js, and modern technologies. 5+ years experience.",
    type: "service",
    category: "Technology",
    price: 50,
    location: "San Francisco, CA",
    postedAt: "2 hours ago",
    images: ["/placeholder-okcta.png"],
    seller: {
      id: "1",
      name: "Alex Chen",
      avatar: "/professional-man.png",
      rating: 4.9,
      verified: true,
    },
    featured: true,
    urgent: false,
  },
  {
    id: "2",
    title: 'MacBook Pro 16" M2 - Like New',
    description: "Barely used MacBook Pro with 32GB RAM, 1TB SSD. Perfect for professionals.",
    type: "product",
    category: "Electronics",
    price: 2800,
    location: "New York, NY",
    postedAt: "4 hours ago",
    images: ["/macbook-air-m2.png"],
    seller: {
      id: "2",
      name: "Sarah Johnson",
      avatar: "/professional-woman.png",
      rating: 4.8,
      verified: true,
    },
    featured: false,
    urgent: true,
  },
  {
    id: "3",
    title: "Home Cleaning Services",
    description: "Professional home cleaning service. Weekly, bi-weekly, or monthly options available.",
    type: "service",
    category: "Home Services",
    price: 80,
    location: "Los Angeles, CA",
    postedAt: "1 day ago",
    images: ["/professional-cleaning-service.png"],
    seller: {
      id: "3",
      name: "Maria Rodriguez",
      avatar: "/diverse-woman-portrait.png",
      rating: 4.7,
      verified: true,
    },
    featured: false,
    urgent: false,
  },
  {
    id: "4",
    title: "Vintage Leather Sofa - Excellent Condition",
    description: "Beautiful vintage leather sofa, perfect for living room. Well maintained.",
    type: "product",
    category: "Furniture",
    price: 450,
    location: "Chicago, IL",
    postedAt: "2 days ago",
    images: ["/vintage-leather-sofa.png"],
    seller: {
      id: "4",
      name: "David Wilson",
      avatar: "/thoughtful-man.png",
      rating: 4.6,
      verified: false,
    },
    featured: false,
    urgent: false,
  },
]

export default function AdsPage() {
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [selectedType, setSelectedType] = useState("all")
  const [sortBy, setSortBy] = useState("recent")
  const [favorites, setFavorites] = useState<string[]>([])

  const categories = [
    "Technology",
    "Electronics",
    "Home Services",
    "Furniture",
    "Fashion",
    "Automotive",
    "Health & Beauty",
    "Education",
    "Other",
  ]

  const filteredAds = mockAds.filter((ad) => {
    const matchesSearch =
      ad.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      ad.description.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesCategory = selectedCategory === "all" || ad.category === selectedCategory
    const matchesType = selectedType === "all" || ad.type === selectedType
    return matchesSearch && matchesCategory && matchesType
  })

  const sortedAds = [...filteredAds].sort((a, b) => {
    switch (sortBy) {
      case "price-low":
        return a.price - b.price
      case "price-high":
        return b.price - a.price
      case "rating":
        return b.seller.rating - a.seller.rating
      default:
        return 0 // Keep original order for 'recent'
    }
  })

  const toggleFavorite = (adId: string) => {
    setFavorites((prev) => (prev.includes(adId) ? prev.filter((id) => id !== adId) : [...prev, adId]))
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-2xl font-bold">Advertisements</h1>
            <Link href="/ads/post">
              <Button className="bg-primary hover:bg-primary/90">
                <Plus className="w-4 h-4 mr-2" />
                Post Ad
              </Button>
            </Link>
          </div>

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

            <Tabs value={selectedType} onValueChange={setSelectedType} className="w-full">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="all">All Ads</TabsTrigger>
                <TabsTrigger value="product">Products</TabsTrigger>
                <TabsTrigger value="service">Services</TabsTrigger>
              </TabsList>
            </Tabs>

            <div className="flex gap-2 overflow-x-auto pb-2">
              <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="Category" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Categories</SelectItem>
                  {categories.map((category) => (
                    <SelectItem key={category} value={category}>
                      {category}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="recent">Most Recent</SelectItem>
                  <SelectItem value="price-low">Price: Low to High</SelectItem>
                  <SelectItem value="price-high">Price: High to Low</SelectItem>
                  <SelectItem value="rating">Highest Rated</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </div>

      {/* Ads Grid */}
      <div className="container mx-auto px-4 py-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {sortedAds.map((ad) => (
            <Card key={ad.id} className="overflow-hidden hover:shadow-lg transition-shadow">
              <div className="relative">
                <img src={ad.images[0] || "/placeholder.svg"} alt={ad.title} className="w-full h-48 object-cover" />
                <div className="absolute top-2 left-2 flex gap-1">
                  {ad.featured && <Badge className="bg-amber-500 hover:bg-amber-600">Featured</Badge>}
                  {ad.urgent && <Badge variant="destructive">Urgent</Badge>}
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute top-2 right-2 bg-white/80 hover:bg-white"
                  onClick={() => toggleFavorite(ad.id)}
                >
                  <Heart
                    className={`w-4 h-4 ${favorites.includes(ad.id) ? "fill-red-500 text-red-500" : "text-gray-600"}`}
                  />
                </Button>
              </div>

              <CardHeader className="pb-2">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <Badge variant="outline" className="mb-2">
                      {ad.type === "product" ? "Product" : "Service"}
                    </Badge>
                    <CardTitle className="text-lg line-clamp-2">{ad.title}</CardTitle>
                  </div>
                </div>
                <p className="text-2xl font-bold text-primary">
                  ${ad.price}
                  {ad.type === "service" && "/hr"}
                </p>
              </CardHeader>

              <CardContent className="pt-0">
                <p className="text-sm text-muted-foreground line-clamp-2 mb-3">{ad.description}</p>

                <div className="flex items-center gap-2 mb-3">
                  <Avatar className="w-6 h-6">
                    <AvatarImage src={ad.seller.avatar || "/placeholder.svg"} />
                    <AvatarFallback>{ad.seller.name[0]}</AvatarFallback>
                  </Avatar>
                  <span className="text-sm font-medium">{ad.seller.name}</span>
                  {ad.seller.verified && (
                    <Badge variant="secondary" className="text-xs">
                      Verified
                    </Badge>
                  )}
                  <div className="flex items-center gap-1 ml-auto">
                    <Star className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                    <span className="text-xs">{ad.seller.rating}</span>
                  </div>
                </div>

                <div className="flex items-center gap-4 text-xs text-muted-foreground mb-4">
                  <div className="flex items-center gap-1">
                    <MapPin className="w-3 h-3" />
                    {ad.location}
                  </div>
                  <div className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {ad.postedAt}
                  </div>
                </div>

                <div className="flex gap-2">
                  <Link href={`/ads/${ad.id}`} className="flex-1">
                    <Button variant="outline" className="w-full bg-transparent">
                      View Details
                    </Button>
                  </Link>
                  <Button size="sm" variant="ghost">
                    <MessageCircle className="w-4 h-4" />
                  </Button>
                  <Button size="sm" variant="ghost">
                    <Phone className="w-4 h-4" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {sortedAds.length === 0 && (
          <div className="text-center py-12">
            <p className="text-muted-foreground">No ads found matching your criteria.</p>
          </div>
        )}
      </div>
    </div>
  )
}
