"use client"

import { useState } from "react"
import { Search, Filter, Plus, MapPin, Star, Heart, ShoppingCart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardFooter } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import Link from "next/link"

interface Product {
  id: string
  title: string
  price: number
  description: string
  images: string[]
  category: string
  condition: "new" | "like-new" | "good" | "fair"
  seller: {
    id: string
    name: string
    avatar: string
    rating: number
    distance: number
  }
  location: string
  postedAt: Date
  isFavorite: boolean
}

const mockProducts: Product[] = [
  {
    id: "1",
    title: "iPhone 14 Pro Max",
    price: 899,
    description: "Excellent condition, barely used. Comes with original box and charger.",
    images: ["/iphone-14-pro-max.png"],
    category: "Electronics",
    condition: "like-new",
    seller: {
      id: "1",
      name: "Sarah Chen",
      avatar: "/professional-woman.png",
      rating: 4.8,
      distance: 0.5,
    },
    location: "Downtown",
    postedAt: new Date(Date.now() - 2 * 60 * 60 * 1000),
    isFavorite: false,
  },
  {
    id: "2",
    title: "MacBook Air M2",
    price: 1200,
    description: "Perfect for students and professionals. 8GB RAM, 256GB SSD.",
    images: ["/macbook-air-m2.png"],
    category: "Electronics",
    condition: "good",
    seller: {
      id: "2",
      name: "Mike Johnson",
      avatar: "/thoughtful-man.png",
      rating: 4.9,
      distance: 1.2,
    },
    location: "Midtown",
    postedAt: new Date(Date.now() - 5 * 60 * 60 * 1000),
    isFavorite: true,
  },
  {
    id: "3",
    title: "Vintage Leather Jacket",
    price: 150,
    description: "Authentic vintage leather jacket, size M. Great for fall weather.",
    images: ["/vintage-leather-jacket.png"],
    category: "Fashion",
    condition: "good",
    seller: {
      id: "3",
      name: "Emma Davis",
      avatar: "/diverse-woman-portrait.png",
      rating: 4.7,
      distance: 2.1,
    },
    location: "Arts District",
    postedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
    isFavorite: false,
  },
  {
    id: "4",
    title: "Gaming Chair",
    price: 200,
    description: "Ergonomic gaming chair with lumbar support. Black and red design.",
    images: ["/ergonomic-gaming-chair.png"],
    category: "Furniture",
    condition: "like-new",
    seller: {
      id: "4",
      name: "Alex Rodriguez",
      avatar: "/man-with-detailed-beard.png",
      rating: 4.6,
      distance: 3.5,
    },
    location: "Tech District",
    postedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
    isFavorite: false,
  },
]

const categories = ["All", "Electronics", "Fashion", "Furniture", "Books", "Sports", "Home", "Other"]

export default function MarketplacePage() {
  const [products, setProducts] = useState<Product[]>(mockProducts)
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("All")
  const [showFilters, setShowFilters] = useState(false)

  const filteredProducts = products.filter((product) => {
    const matchesSearch =
      product.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      product.description.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesCategory = selectedCategory === "All" || product.category === selectedCategory
    return matchesSearch && matchesCategory
  })

  const toggleFavorite = (productId: string) => {
    setProducts((prev) =>
      prev.map((product) => (product.id === productId ? { ...product, isFavorite: !product.isFavorite } : product)),
    )
  }

  const formatTimeAgo = (date: Date) => {
    const now = new Date()
    const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60))

    if (diffInHours < 1) return "Just now"
    if (diffInHours < 24) return `${diffInHours}h ago`
    const diffInDays = Math.floor(diffInHours / 24)
    return `${diffInDays}d ago`
  }

  return (
    <div className="min-h-screen bg-background pb-20">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-background/95 backdrop-blur-sm border-b">
        <div className="p-4">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-2xl font-bold">Marketplace</h1>
            <Link href="/marketplace/sell">
              <Button size="sm" className="bg-primary hover:bg-primary/90">
                <Plus className="h-4 w-4 mr-1" />
                Sell
              </Button>
            </Link>
          </div>

          {/* Search Bar */}
          <div className="relative mb-4">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
            <Input
              placeholder="Search products..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 pr-12"
            />
            <Button
              variant="ghost"
              size="sm"
              className="absolute right-1 top-1/2 transform -translate-y-1/2"
              onClick={() => setShowFilters(!showFilters)}
            >
              <Filter className="h-4 w-4" />
            </Button>
          </div>

          {/* Categories */}
          <div className="flex gap-2 overflow-x-auto pb-2">
            {categories.map((category) => (
              <Button
                key={category}
                variant={selectedCategory === category ? "default" : "outline"}
                size="sm"
                onClick={() => setSelectedCategory(category)}
                className="whitespace-nowrap"
              >
                {category}
              </Button>
            ))}
          </div>
        </div>
      </div>

      {/* Products Grid */}
      <div className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredProducts.map((product) => (
            <Card key={product.id} className="overflow-hidden hover:shadow-lg transition-shadow">
              <div className="relative">
                <img
                  src={product.images[0] || "/placeholder.svg"}
                  alt={product.title}
                  className="w-full h-48 object-cover"
                />
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute top-2 right-2 bg-background/80 hover:bg-background"
                  onClick={() => toggleFavorite(product.id)}
                >
                  <Heart
                    className={`h-4 w-4 ${product.isFavorite ? "fill-red-500 text-red-500" : "text-muted-foreground"}`}
                  />
                </Button>
                <Badge variant="secondary" className="absolute top-2 left-2 bg-background/80">
                  {product.condition}
                </Badge>
              </div>

              <CardContent className="p-4">
                <div className="flex items-start justify-between mb-2">
                  <h3 className="font-semibold text-lg truncate">{product.title}</h3>
                  <span className="text-lg font-bold text-primary">${product.price}</span>
                </div>

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

                <div className="flex items-center gap-2 mb-2">
                  <Avatar className="h-6 w-6">
                    <AvatarImage src={product.seller.avatar || "/placeholder.svg"} />
                    <AvatarFallback>{product.seller.name[0]}</AvatarFallback>
                  </Avatar>
                  <span className="text-sm font-medium">{product.seller.name}</span>
                  <div className="flex items-center gap-1">
                    <Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
                    <span className="text-xs text-muted-foreground">{product.seller.rating}</span>
                  </div>
                </div>

                <div className="flex items-center justify-between text-xs text-muted-foreground">
                  <div className="flex items-center gap-1">
                    <MapPin className="h-3 w-3" />
                    <span>
                      {product.seller.distance}mi • {product.location}
                    </span>
                  </div>
                  <span>{formatTimeAgo(product.postedAt)}</span>
                </div>
              </CardContent>

              <CardFooter className="p-4 pt-0 flex gap-2">
                <Link href={`/marketplace/${product.id}`} className="flex-1">
                  <Button variant="outline" className="w-full bg-transparent">
                    View Details
                  </Button>
                </Link>
                <Link href={`/chat/${product.seller.id}`}>
                  <Button size="sm">
                    <ShoppingCart className="h-4 w-4 mr-1" />
                    Buy
                  </Button>
                </Link>
              </CardFooter>
            </Card>
          ))}
        </div>

        {filteredProducts.length === 0 && (
          <div className="text-center py-12">
            <div className="text-muted-foreground mb-2">No products found</div>
            <p className="text-sm text-muted-foreground">Try adjusting your search or filters</p>
          </div>
        )}
      </div>
    </div>
  )
}
