'use client';

import { useState } from 'react';
import Link from 'next/link';
import ProductCard, { StarRating } from '@/components/product/ProductCard';
import AuctionCountdown from '@/components/product/AuctionCountdown';
import { useCartStore, useWishlistStore, useToastStore } from '@/lib/store';
import type { Product, Review, PayvatoPlan, AuctionBid } from '@/lib/types';

interface Props {
  product: Product;
  related: Product[];
  reviews: Review[];
  payvatoPlans: PayvatoPlan[] | null;
  auctionBids: AuctionBid[] | null;
}

export default function ProductDetailClient({ product, related, reviews, payvatoPlans, auctionBids }: Props) {
  const [qty, setQty] = useState(1);
  const [selectedPlan, setSelectedPlan] = useState<PayvatoPlan | null>(payvatoPlans?.[0] || null);
  const addToCart = useCartStore(s => s.addItem);
  const wishlistToggle = useWishlistStore(s => s.toggle);
  const wishlistHas = useWishlistStore(s => s.has);
  const toast = useToastStore(s => s.show);
  const isWished = wishlistHas(product.id);

  const discount = product.original_price > product.price
    ? Math.round((1 - product.price / product.original_price) * 100)
    : 0;

  function handleAddToCart() {
    addToCart(product, qty);
    toast(`${product.name.substring(0, 30)}... added to cart`, 'success');
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-6">
      {/* Breadcrumb */}
      <nav className="flex items-center gap-2 text-sm text-gray-500 mb-6">
        <Link href="/" className="hover:text-primary">Home</Link>
        <span>/</span>
        <Link href="/category" className="hover:text-primary">Products</Link>
        <span>/</span>
        {product.category && (
          <>
            <Link href={`/category/${product.category.slug}`} className="hover:text-primary">{product.category.name}</Link>
            <span>/</span>
          </>
        )}
        <span className="text-gray-800 font-semibold line-clamp-1">{product.name}</span>
      </nav>

      <div className="grid md:grid-cols-2 gap-8 mb-12">
        {/* Image */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4">
          <div className="relative overflow-hidden rounded-xl bg-gray-50">
            <img src={product.image_url} alt={product.name} className="w-full h-96 object-cover" />
            {product.badge && (
              <span className="absolute top-4 left-4 bg-red-500 text-white text-xs font-bold px-3 py-1.5 rounded-full">{product.badge}</span>
            )}
            {product.is_auction && product.auction_end_time && (
              <div className="absolute bottom-0 left-0 right-0">
                <AuctionCountdown endTime={product.auction_end_time} productId={product.id} />
              </div>
            )}
          </div>
        </div>

        {/* Details */}
        <div className="space-y-4">
          <div>
            <p className="text-sm text-blue-600 font-semibold uppercase tracking-wide mb-1">{product.brand}</p>
            <h1 className="text-2xl md:text-3xl font-black text-gray-900 mb-2">{product.name}</h1>
            <div className="flex items-center gap-3">
              <StarRating rating={product.rating} />
              <span className="text-sm text-gray-500">{product.rating} ({product.reviews_count.toLocaleString()} reviews)</span>
            </div>
          </div>

          {/* Price */}
          <div className="bg-white rounded-xl p-4 border border-gray-100">
            <div className="flex items-baseline gap-3">
              <span className="text-3xl font-black text-gray-900">${product.price.toFixed(2)}</span>
              {discount > 0 && (
                <>
                  <span className="text-lg text-gray-400 line-through">${product.original_price.toFixed(2)}</span>
                  <span className="bg-red-100 text-red-600 text-sm font-bold px-2 py-0.5 rounded-full">-{discount}%</span>
                </>
              )}
            </div>
            <p className="text-xs text-green-600 font-semibold mt-1">✓ In Stock • Free Shipping over $49</p>
          </div>

          {/* Payvato Pay-Over-Time */}
          {payvatoPlans && payvatoPlans.length > 0 && (
            <div className="bg-emerald-50 rounded-xl p-4 border border-emerald-200">
              <div className="flex items-center gap-2 mb-3">
                <span className="payvato-badge text-white text-xs font-bold px-2.5 py-1 rounded-full">💳 Payvato</span>
                <span className="text-sm font-bold text-emerald-800">Pay Over Time</span>
              </div>
              <div className="grid grid-cols-3 gap-2">
                {payvatoPlans.map(plan => (
                  <button key={plan.id} onClick={() => setSelectedPlan(plan)}
                    className={`p-3 rounded-lg border-2 text-center transition-all ${selectedPlan?.id === plan.id ? 'border-emerald-500 bg-white shadow' : 'border-emerald-100 hover:border-emerald-300'}`}>
                    <div className="text-lg font-black text-emerald-700">${plan.monthly_payment.toFixed(2)}</div>
                    <div className="text-xs text-emerald-600 font-semibold">/month × {plan.installment_months}</div>
                    {plan.interest_rate > 0 && <div className="text-xs text-gray-400 mt-0.5">{plan.interest_rate}% APR</div>}
                    {plan.interest_rate === 0 && <div className="text-xs text-emerald-500 font-bold mt-0.5">0% Interest!</div>}
                  </button>
                ))}
              </div>
              <p className="text-xs text-emerald-600 mt-2">Powered by <a href="https://payvato.com" target="_blank" rel="noopener noreferrer" className="font-bold underline">Payvato</a> • Instant approval</p>
            </div>
          )}

          {/* Auction Bids */}
          {product.is_auction && auctionBids && auctionBids.length > 0 && (
            <div className="bg-gray-900 rounded-xl p-4 text-white">
              <h3 className="font-bold text-sm mb-2">Recent Bids</h3>
              <div className="space-y-1">
                {auctionBids.slice(0, 3).map((bid, i) => (
                  <div key={bid.id} className="flex items-center justify-between text-sm">
                    <span className="text-gray-300">{i === 0 ? '🥇' : i === 1 ? '🥈' : '🥉'} {bid.user?.first_name} {bid.user?.last_name?.charAt(0)}.</span>
                    <span className="font-bold text-accent">${bid.bid_amount.toFixed(2)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Description */}
          <p className="text-gray-600 leading-relaxed">{product.description}</p>

          {/* Specs */}
          {product.specs && Object.keys(product.specs).length > 0 && (
            <div className="bg-gray-50 rounded-xl p-4">
              <h3 className="font-bold text-sm text-gray-800 mb-3">Specifications</h3>
              <div className="grid grid-cols-2 gap-2">
                {Object.entries(product.specs).map(([key, value]) => (
                  <div key={key} className="flex justify-between text-sm py-1.5 border-b border-gray-100">
                    <span className="text-gray-500">{key}</span>
                    <span className="text-gray-800 font-medium">{value}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Add to Cart */}
          <div className="flex items-center gap-3">
            <div className="flex items-center border border-gray-200 rounded-xl overflow-hidden">
              <button onClick={() => setQty(Math.max(1, qty - 1))} className="px-4 py-3 text-gray-600 hover:bg-gray-50 font-bold">−</button>
              <input type="number" value={qty} onChange={e => setQty(Math.max(1, parseInt(e.target.value) || 1))} className="w-12 text-center text-sm font-bold qty-input border-x border-gray-200 py-3" />
              <button onClick={() => setQty(qty + 1)} className="px-4 py-3 text-gray-600 hover:bg-gray-50 font-bold">+</button>
            </div>
            <button onClick={handleAddToCart} className="flex-1 btn-accent py-3.5 rounded-xl font-bold text-sm flex items-center justify-center gap-2">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
              {product.is_auction ? 'Place Bid' : 'Add to Cart'}
            </button>
            <button onClick={() => { wishlistToggle(product.id); toast(isWished ? 'Removed from wishlist' : 'Added to wishlist', isWished ? 'info' : 'success'); }}
              className={`p-3.5 rounded-xl border ${isWished ? 'bg-red-50 border-red-200 text-red-500' : 'border-gray-200 text-gray-400 hover:text-red-500'}`}>
              <svg className="w-5 h-5 fill-current" viewBox="0 0 20 20"><path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"/></svg>
            </button>
          </div>
        </div>
      </div>

      {/* Reviews */}
      {reviews.length > 0 && (
        <section className="mb-12">
          <h2 className="text-2xl font-black text-gray-900 mb-6">Customer Reviews</h2>
          <div className="grid md:grid-cols-2 gap-4">
            {reviews.map(r => (
              <div key={r.id} className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
                <div className="flex items-center gap-3 mb-3">
                  <img src={r.user?.avatar_url || `https://ui-avatars.com/api/?name=${r.user?.first_name}+${r.user?.last_name}&background=003087&color=fff&size=40`}
                    alt="Reviewer" className="w-10 h-10 rounded-full object-cover" />
                  <div>
                    <p className="font-semibold text-sm text-gray-800">{r.user?.first_name} {r.user?.last_name}</p>
                    <StarRating rating={r.rating} />
                  </div>
                  {r.verified_purchase && <span className="ml-auto text-xs bg-green-100 text-green-700 font-semibold px-2 py-1 rounded-full">✓ Verified</span>}
                </div>
                {r.title && <h4 className="font-bold text-sm text-gray-800 mb-1">{r.title}</h4>}
                <p className="text-sm text-gray-600 leading-relaxed">{r.content}</p>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Related Products */}
      {related.length > 0 && (
        <section>
          <h2 className="text-2xl font-black text-gray-900 mb-6">You Might Also Like</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {related.map(p => <ProductCard key={p.id} product={p} />)}
          </div>
        </section>
      )}
    </div>
  );
}
