'use client'

import { useState } from 'react'
import { useCartStore } from '../store/cart'
import { formatTL } from '../lib/format'

interface Product {
  id: number
  slug: string
  nameTr: string
  category: string
  size: string | null
  priceB2B: number
  stock: number
  images: string
}

interface ProductCardProps {
  product: Product
  discountedPrice: number
  discountRate: number
}

const CATEGORY_LABEL: Record<string, string> = {
  CUBO: 'Cubo',
  RECTA: 'Recta',
  GLOBE: 'Globe',
  OTHER: 'Diğer',
}

export default function ProductCard({
  product,
  discountedPrice,
  discountRate,
}: ProductCardProps) {
  const addItem = useCartStore((s) => s.addItem)
  const [added, setAdded] = useState(false)

  const images = (() => {
    try {
      return JSON.parse(product.images) as string[]
    } catch {
      return []
    }
  })()

  function handleAdd() {
    addItem({
      productId: product.id,
      slug: product.slug,
      nameTr: product.nameTr,
      priceB2B: product.priceB2B,
      discountedPrice,
      quantity: 1,
      size: product.size,
    })
    setAdded(true)
    setTimeout(() => setAdded(false), 2000)
  }

  return (
    <div className="bg-white shadow-sm rounded-xl overflow-hidden group flex flex-col">
      <div className="aspect-square bg-sand overflow-hidden">
        {images[0] ? (
          <img
            src={images[0]}
            alt={product.nameTr}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <span className="font-display text-5xl text-earth/20">
              {product.nameTr[0]}
            </span>
          </div>
        )}
      </div>

      <div className="p-4 flex flex-col flex-1">
        <p className="font-body text-xs text-earth/70 tracking-widest uppercase mb-1">
          {CATEGORY_LABEL[product.category] ?? product.category}
        </p>
        <h3 className="font-display text-lg text-brown">{product.nameTr}</h3>
        {product.size && (
          <p className="font-body text-xs text-brown/50 mt-0.5">{product.size}</p>
        )}

        <div className="mt-auto pt-4 flex items-end justify-between">
          <div>
            {discountRate > 0 ? (
              <>
                <p className="font-body text-xs text-brown/40 line-through">
                  {formatTL(product.priceB2B)}
                </p>
                <p className="font-body text-sm font-medium text-earth">
                  {formatTL(discountedPrice)}
                </p>
              </>
            ) : (
              <p className="font-body text-sm font-medium text-brown">
                {formatTL(product.priceB2B)}
              </p>
            )}
            <p className="font-body text-xs text-brown/40 mt-0.5">
              Stok: {product.stock}
            </p>
          </div>

          <button
            onClick={handleAdd}
            disabled={product.stock === 0}
            className={`px-3 py-1.5 rounded-lg font-body text-xs tracking-wide transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${
              added
                ? 'bg-green-700 text-white'
                : 'bg-brown text-cream hover:bg-earth'
            }`}
          >
            {product.stock === 0 ? 'Stok Yok' : added ? 'Eklendi ✓' : 'Sepete Ekle'}
          </button>
        </div>
      </div>
    </div>
  )
}
