"use client"

import { useState, useEffect } from "react"
import { ArrowLeft, Heart, Share2, MapPin, Star, MessageCircle, Phone, Shield, Clock } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { useRouter } from "next/navigation"
import Link from "next/link"

interface ProductDetails {
  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
    reviewCount: number
    responseTime: string
    joinedDate: string
    distance: number
  }
  location: string
  postedAt: Date
  views: number
  isFavorite: boolean
  specifications?: { [key: string]: string }
}

export default function ProductDetailsPage({ params }: { params: { productId: string } }) {
  const router = useRouter()
  const [product, setProduct] = useState<ProductDetails | null>(null)
  const [currentImageIndex, setCurrentImageIndex] = useState(0)
  const [isFavorite, setIsFavorite] = useState(false)

  useEffect(() => {
    // Mock product data - in real app, fetch from API
    const mockProduct: ProductDetails = {
      id: params.productId,
      title: "iPhone 14 Pro Max",
      price: 899,
      description:
        "Excellent condition iPhone 14 Pro Max in Deep Purple. Barely used for 3 months, always kept in a case with screen protector. Comes with original box, charger, and unused EarPods. Battery health is at 100%. No scratches or dents, looks brand new. Perfect for someone looking for a premium phone at a great price.",
      images: [
        "/iphone-14-pro-max-front.png",
        "/iphone-14-pro-max-back.png",
        "/iphone-14-pro-max-box.png",
        "/iphone-14-pro-max-accessories.png",
      ],
      category: "Electronics",
      condition: "like-new",
      seller: {
        id: "1",
        name: "Sarah Chen",
        avatar: "/professional-woman.png",
        rating: 4.8,
        reviewCount: 47,
        responseTime: "Usually responds within an hour",
        joinedDate: "March 2022",
        distance: 0.5,
      },
      location: "Downtown, San Francisco",
      postedAt: new Date(Date.now() - 2 * 60 * 60 * 1000),
      views: 23,
      isFavorite: false,
      specifications: {
        Storage: "256GB",
        Color: "Deep Purple",
        Carrier: "Unlocked",
        "Battery Health": "100%",
        Warranty: "Apple Care+ until Dec 2024",
      },
    }

    setProduct(mockProduct)
    setIsFavorite(mockProduct.isFavorite)
  }, [params.productId])

  const toggleFavorite = () => {
    setIsFavorite(!isFavorite)
  }

  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`
  }

  if (!product) {
    return <div className="min-h-screen bg-background flex items-center justify-center">Loading...</div>
  }

  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="flex items-center justify-between p-4">
          <Button variant="ghost" size="sm" onClick={() => router.back()}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div className="flex gap-2">
            <Button variant="ghost" size="sm" onClick={toggleFavorite}>
              <Heart className={`h-4 w-4 ${isFavorite ? "fill-red-500 text-red-500" : ""}`} />
            </Button>
            <Button variant="ghost" size="sm">
              <Share2 className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* Image Gallery */}
      <div className="relative">
        <div className="aspect-square overflow-hidden">
          <img
            src={product.images[currentImageIndex] || "/placeholder.svg"}
            alt={product.title}
            className="w-full h-full object-cover"
          />
        </div>
        {product.images.length > 1 && (
          <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex gap-2">
            {product.images.map((_, index) => (
              <button
                key={index}
                className={`w-2 h-2 rounded-full ${index === currentImageIndex ? "bg-white" : "bg-white/50"}`}
                onClick={() => setCurrentImageIndex(index)}
              />
            ))}
          </div>
        )}
        <Badge className="absolute top-4 left-4 bg-background/80 text-foreground">{product.condition}</Badge>
      </div>

      <div className="p-4 space-y-6">
        {/* Product Info */}
        <div>
          <div className="flex items-start justify-between mb-2">
            <h1 className="text-2xl font-bold">{product.title}</h1>
            <span className="text-2xl font-bold text-primary">${product.price}</span>
          </div>
          <div className="flex items-center gap-4 text-sm text-muted-foreground mb-4">
            <div className="flex items-center gap-1">
              <MapPin className="h-4 w-4" />
              <span>{product.location}</span>
            </div>
            <div className="flex items-center gap-1">
              <Clock className="h-4 w-4" />
              <span>{formatTimeAgo(product.postedAt)}</span>
            </div>
            <span>{product.views} views</span>
          </div>
          <p className="text-muted-foreground leading-relaxed">{product.description}</p>
        </div>

        {/* Specifications */}
        {product.specifications && (
          <Card>
            <CardContent className="p-4">
              <h3 className="font-semibold mb-3">Specifications</h3>
              <div className="space-y-2">
                {Object.entries(product.specifications).map(([key, value]) => (
                  <div key={key} className="flex justify-between">
                    <span className="text-muted-foreground">{key}</span>
                    <span className="font-medium">{value}</span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Seller Info */}
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3 mb-4">
              <Avatar className="h-12 w-12">
                <AvatarImage src={product.seller.avatar || "/placeholder.svg"} />
                <AvatarFallback>{product.seller.name[0]}</AvatarFallback>
              </Avatar>
              <div className="flex-1">
                <h3 className="font-semibold">{product.seller.name}</h3>
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <div className="flex items-center gap-1">
                    <Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
                    <span>
                      {product.seller.rating} ({product.seller.reviewCount} reviews)
                    </span>
                  </div>
                  <span>•</span>
                  <span>{product.seller.distance}mi away</span>
                </div>
              </div>
            </div>

            <div className="space-y-2 text-sm">
              <div className="flex items-center gap-2 text-muted-foreground">
                <Shield className="h-4 w-4" />
                <span>{product.seller.responseTime}</span>
              </div>
              <div className="flex items-center gap-2 text-muted-foreground">
                <Clock className="h-4 w-4" />
                <span>Joined {product.seller.joinedDate}</span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Action Buttons */}
        <div className="flex gap-3">
          <Link href={`/chat/${product.seller.id}`} className="flex-1">
            <Button className="w-full">
              <MessageCircle className="h-4 w-4 mr-2" />
              Message Seller
            </Button>
          </Link>
          <Link href={`/call/${product.seller.id}`}>
            <Button variant="outline" size="lg">
              <Phone className="h-4 w-4" />
            </Button>
          </Link>
        </div>

        {/* Safety Tips */}
        <Card className="bg-muted/50">
          <CardContent className="p-4">
            <div className="flex items-start gap-3">
              <Shield className="h-5 w-5 text-primary mt-0.5" />
              <div>
                <h4 className="font-medium mb-1">Stay Safe</h4>
                <p className="text-sm text-muted-foreground">
                  Meet in a public place, inspect the item before paying, and trust your instincts.
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
