'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import CartIcon from '../../components/CartIcon'

// Convert EUR to BGN and round to nearest 0.10
const convertToBGN = (eur: number | null | undefined): string => {
  if (!eur || eur === 0) return '0.00'
  const bgn = eur * 1.95583
  // Round to nearest 0.10 (e.g., 58.68 -> 58.70, 58.86 -> 58.90)
  const rounded = Math.round(bgn * 10) / 10
  return rounded.toFixed(2)
}

interface Product {
  id: number
  name: string
  price: number
  description: string
  sizes: string[]
  colors: { name: string; hex: string }[]
  images: string[]
}

export default function ProductPage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const productId = parseInt(params.id)
  const [product, setProduct] = useState<Product | null>(null)
  const [loading, setLoading] = useState(true)
  const [selectedSize, setSelectedSize] = useState<string>('M')
  const [selectedColor, setSelectedColor] = useState<number>(0)
  const [isFavorite, setIsFavorite] = useState(false)
  const [showSizeChart, setShowSizeChart] = useState(false)
  const [currentImageIndex, setCurrentImageIndex] = useState(0)

  useEffect(() => {
    fetch('/api/products')
      .then(res => res.json())
      .then(data => {
        const foundProduct = data.find((p: Product) => p.id === productId)
        if (foundProduct) {
          // Ensure images array exists
          if (!foundProduct.images || foundProduct.images.length === 0) {
            foundProduct.images = []
          }
          setProduct(foundProduct)
          if (foundProduct.sizes && foundProduct.sizes.length > 0) {
            setSelectedSize(foundProduct.sizes[0])
          }
        }
        setLoading(false)
      })
      .catch(err => {
        console.error('Error loading product:', err)
        setLoading(false)
      })
  }, [productId])

  const sizeChartData = [
    { size: 'XXXS', measurements: ['70-73', '57-59', '80-83'] },
    { size: 'XXS', measurements: ['74-77', '60-62', '84-87'] },
    { size: 'XS', measurements: ['78-81', '63-65', '88-91'] },
    { size: 'S', measurements: ['82-85', '66-69', '92-95'] },
    { size: 'M', measurements: ['86-89', '70-73', '96-98'] },
    { size: 'L', measurements: ['90-93', '74-77', '99-102'] },
    { size: 'XL', measurements: ['94-97', '78-81', '103-106'] },
  ]

  if (loading) {
    return (
      <div className="min-h-screen bg-[#F5F5F5] flex items-center justify-center">
        <div className="text-center">
          <p className="text-medium-grey">Зареждане на продукт...</p>
        </div>
      </div>
    )
  }

  if (!product) {
    return (
      <div className="min-h-screen bg-[#F5F5F5] flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-dark-grey mb-4">Продуктът не е намерен</h1>
          <Link href="/" className="text-medium-grey hover:text-dark-grey">
            Назад към началната страница
          </Link>
        </div>
      </div>
    )
  }

  const handleAddToCart = () => {
    if (typeof window === 'undefined') return
    const cart = JSON.parse(localStorage.getItem('cart') || '[]')
    cart.push({
      productId: product.id,
      name: product.name,
      price: product.price,
      size: selectedSize,
      color: product.colors[selectedColor].name,
    })
    localStorage.setItem('cart', JSON.stringify(cart))
    window.dispatchEvent(new Event('cartUpdated'))
    alert('Продуктът е добавен в количката!')
  }

  return (
    <div className="min-h-screen bg-[#F5F5F5] relative">
      {/* Announcement Bar */}
      <div className="bg-black text-white text-center py-2 text-sm font-medium relative z-30">
        БЕЗПЛАТНА ДОСТАВКА НАД 35€
      </div>

          {/* Header */}
          <header className="absolute top-8 left-0 right-0 z-20 bg-transparent">
            <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <button
              onClick={() => router.back()}
              className="w-10 h-10 rounded-full bg-white bg-opacity-80 flex items-center justify-center backdrop-blur-sm"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-6 w-6 text-dark-grey"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
              </svg>
            </button>
            <CartIcon />
          </div>
        </div>
      </header>

      {/* Product Image - Full Screen */}
      <div className="relative h-[60vh] bg-white">
        {product.images && product.images.length > 0 ? (
          <>
            <img
              src={`/images/products/${product.images[currentImageIndex]}`}
              alt={`${product.name} - Изображение ${currentImageIndex + 1}`}
              className="w-full h-full object-cover"
              onError={(e) => {
                const target = e.currentTarget as HTMLImageElement
                target.style.display = 'none'
                // Show placeholder div if image fails
                const placeholder = target.parentElement?.querySelector('.image-placeholder-main') as HTMLElement
                if (placeholder) placeholder.style.display = 'flex'
              }}
            />
            
            {/* Navigation Arrows */}
            {product.images.length > 1 && (
              <>
                <button
                  onClick={() => setCurrentImageIndex((prev) => 
                    prev === 0 ? product.images.length - 1 : prev - 1
                  )}
                  className="absolute left-4 top-1/2 transform -translate-y-1/2 w-10 h-10 rounded-full bg-white bg-opacity-80 flex items-center justify-center backdrop-blur-sm hover:bg-opacity-100 transition"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-6 w-6 text-dark-grey"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
                  </svg>
                </button>
                <button
                  onClick={() => setCurrentImageIndex((prev) => 
                    prev === product.images.length - 1 ? 0 : prev + 1
                  )}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 w-10 h-10 rounded-full bg-white bg-opacity-80 flex items-center justify-center backdrop-blur-sm hover:bg-opacity-100 transition"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-6 w-6 text-dark-grey"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </>
            )}
          </>
        ) : (
          <div className="image-placeholder-main w-full h-full bg-gradient-to-br from-gray-200 to-gray-300 flex items-center justify-center">
            <span className="text-medium-grey text-sm">Изображение</span>
          </div>
        )}
        {/* Fallback placeholder (hidden by default, shown on error) */}
        <div className="image-placeholder-main hidden w-full h-full bg-gradient-to-br from-gray-200 to-gray-300 absolute inset-0 flex items-center justify-center">
          <span className="text-medium-grey text-sm">Изображение</span>
        </div>
        
        {/* Image Dots Indicator */}
        {product.images && 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}
                onClick={() => setCurrentImageIndex(index)}
                className={`w-2 h-2 rounded-full transition-all ${
                  index === currentImageIndex 
                    ? 'bg-dark-grey w-6' 
                    : 'bg-white bg-opacity-50 hover:bg-opacity-75'
                }`}
                aria-label={`Покажи изображение ${index + 1}`}
              />
            ))}
          </div>
        )}

        {/* Favorite Icon */}
        <button
          onClick={() => setIsFavorite(!isFavorite)}
          className="absolute right-4 bottom-20 w-10 h-10 rounded-full bg-white bg-opacity-80 flex items-center justify-center backdrop-blur-sm"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className={`h-6 w-6 ${isFavorite ? 'fill-red-500 text-red-500' : 'text-dark-grey'}`}
            viewBox="0 0 24 24"
            fill={isFavorite ? 'currentColor' : 'none'}
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
            />
          </svg>
        </button>
      </div>

      {/* Product Details Card - Overlay */}
      <div className="relative -mt-8 bg-white rounded-t-3xl pt-6 px-4 pb-8 min-h-[50vh]">
        {/* Color Swatches - Positioned at top right of white card */}
        <div className="absolute right-4 top-6 flex flex-col gap-3">
          {product.colors.map((color, index) => (
            <button
              key={index}
              onClick={() => setSelectedColor(index)}
              className={`w-10 h-10 rounded-full border-2 transition-all ${
                selectedColor === index
                  ? 'border-dark-grey scale-110'
                  : 'border-gray-200 hover:border-medium-grey'
              }`}
              style={{ backgroundColor: color.hex }}
              title={color.name}
            />
          ))}
        </div>

        <div className="max-w-3xl mx-auto pr-16">
          <h1 className="text-2xl font-bold text-dark-grey mb-2">{product.name}</h1>
          <p className="text-2xl font-semibold text-dark-grey mb-6">€{product.price ? product.price.toFixed(0) : '0'} ({convertToBGN(product.price)} лв)</p>

          {/* Size Selection */}
          <div className="mb-6">
            <div className="flex items-center gap-2 mb-3">
              <h3 className="text-sm font-medium text-dark-grey">Вашият размер</h3>
              <span className="text-sm text-medium-grey">-</span>
              <button
                onClick={() => setShowSizeChart(true)}
                className="text-sm text-medium-grey hover:text-dark-grey underline"
              >
                Таблица с размери
              </button>
            </div>
            <div className="flex gap-3">
              {product.sizes.map((size) => (
                <button
                  key={size}
                  onClick={() => setSelectedSize(size)}
                  className={`w-12 h-12 rounded-lg border-2 flex items-center justify-center font-medium transition-all ${
                    selectedSize === size
                      ? 'bg-light-pink border-light-pink text-dark-grey'
                      : 'border-gray-200 text-medium-grey hover:border-light-pink'
                  }`}
                >
                  {size}
                </button>
              ))}
            </div>
          </div>

          {/* Color Selection */}
          <div className="mb-8">
            <h3 className="text-sm font-medium text-dark-grey mb-3">Цвят</h3>
            <p className="text-sm text-medium-grey">{product.colors[selectedColor].name}</p>
          </div>

          {/* Add to Cart Button */}
          <button
            onClick={handleAddToCart}
            className="w-full py-4 bg-dark-grey text-white font-semibold rounded-lg hover:bg-opacity-90 transition mb-4 text-center"
          >
            Добави в количката
          </button>
        </div>
      </div>

      {/* Size Chart Modal */}
      {showSizeChart && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
          onClick={() => setShowSizeChart(false)}
        >
          <div
            className="bg-white rounded-lg max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold text-dark-grey">Таблица с размери</h2>
              <button
                onClick={() => setShowSizeChart(false)}
                className="text-medium-grey hover:text-dark-grey"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="h-6 w-6"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="border-b border-gray-200">
                    <th className="text-left py-3 px-4 text-sm font-medium text-dark-grey">Размер</th>
                    <th className="text-center py-3 px-4 text-sm font-medium text-dark-grey">Гръдна обиколка</th>
                    <th className="text-center py-3 px-4 text-sm font-medium text-dark-grey">Талия</th>
                    <th className="text-center py-3 px-4 text-sm font-medium text-dark-grey">Бедра</th>
                  </tr>
                </thead>
                <tbody>
                  {sizeChartData.map((row, index) => (
                    <tr
                      key={row.size}
                      className={`border-b border-gray-100 ${
                        index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
                      }`}
                    >
                      <td className="py-3 px-4 text-sm font-medium text-dark-grey">{row.size}</td>
                      <td className="py-3 px-4 text-sm text-medium-grey text-center">{row.measurements[0]}</td>
                      <td className="py-3 px-4 text-sm text-medium-grey text-center">{row.measurements[1]}</td>
                      <td className="py-3 px-4 text-sm text-medium-grey text-center">{row.measurements[2]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <p className="text-xs text-medium-grey mt-4 text-center">
              Размерите са в сантиметри (см)
            </p>
          </div>
        </div>
      )}

      {/* Footer */}
      <footer className="bg-white border-t border-gray-200 mt-12">
        <div className="max-w-7xl mx-auto px-4 py-8">
          <div className="grid grid-cols-2 gap-6 mb-6">
            <div>
              <h3 className="text-sm font-semibold text-dark-grey mb-3">За нас</h3>
              <ul className="space-y-2">
                <li>
                  <a href="#" className="text-sm text-medium-grey hover:text-dark-grey transition">
                    За нас
                  </a>
                </li>
                <li>
                  <a href="#" className="text-sm text-medium-grey hover:text-dark-grey transition">
                    Контакти
                  </a>
                </li>
                <li>
                  <a href="#" className="text-sm text-medium-grey hover:text-dark-grey transition">
                    Доставка и връщане
                  </a>
                </li>
              </ul>
            </div>
            <div>
              <h3 className="text-sm font-semibold text-dark-grey mb-3">Помощ</h3>
              <ul className="space-y-2">
                <li>
                  <a href="#" className="text-sm text-medium-grey hover:text-dark-grey transition">
                    Често задавани въпроси
                  </a>
                </li>
                <li>
                  <a href="#" className="text-sm text-medium-grey hover:text-dark-grey transition">
                    Размери
                  </a>
                </li>
                <li>
                  <a href="#" className="text-sm text-medium-grey hover:text-dark-grey transition">
                    Условия за ползване
                  </a>
                </li>
              </ul>
            </div>
          </div>
          <div className="pt-6 border-t border-gray-200 text-center">
            <p className="text-xs text-medium-grey">
              © {new Date().getFullYear()} seksi.bg. Всички права запазени.
            </p>
          </div>
        </div>
      </footer>
    </div>
  )
}
