'use client'

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

// 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 CartItem {
  productId: number
  name: string
  price: number
  size: string | null
  color: string | null
  image?: string | null
}

interface Product {
  id: number
  name: string
  images: string[]
}

export default function CartPage() {
  const router = useRouter()
  const [cart, setCart] = useState<CartItem[]>([])

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const cartData: CartItem[] = JSON.parse(localStorage.getItem('cart') || '[]')
      
      // Fetch product images for cart items
      fetch('/api/products')
        .then(res => res.json())
        .then((products: Product[]) => {
          const cartWithImages = cartData.map(item => {
            const product = products.find(p => p.id === item.productId)
            if (product && product.images && product.images.length > 0) {
              return {
                ...item,
                image: product.images[0]
              }
            }
            return {
              ...item,
              image: null
            }
          })
          setCart(cartWithImages)
        })
        .catch(() => {
          // If API fails, just use cart data without images
          setCart(cartData)
        })
    }
  }, [])

  const removeFromCart = (index: number) => {
    const newCart = cart.filter((_, i) => i !== index)
    setCart(newCart)
    if (typeof window !== 'undefined') {
      localStorage.setItem('cart', JSON.stringify(newCart))
      // Dispatch custom event to update cart icon
      window.dispatchEvent(new Event('cartUpdated'))
    }
  }

  const total = cart.reduce((sum, item) => sum + (item.price || 0), 0)

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

      {/* Header */}
      <header className="bg-white">
        <div className="max-w-4xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <Link href="/" className="text-xl font-bold text-dark-grey">
              ← Назад
            </Link>
            <Link href="/cart" className="relative inline-block">
              <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="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>
              {cart.length > 0 && (
                <span className="absolute -top-2 -right-2 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                  {cart.length}
                </span>
              )}
            </Link>
          </div>
        </div>
      </header>

      <div className="max-w-4xl mx-auto px-4 py-6">
        <h1 className="text-2xl font-bold text-dark-grey mb-6">Количка</h1>

        {cart.length === 0 ? (
          <div className="text-center py-12 bg-white rounded-lg">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-24 w-24 text-medium-grey mx-auto mb-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                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>
            <p className="text-medium-grey mb-4">Вашата количка е празна.</p>
            <Link
              href="/"
              className="inline-block px-6 py-3 bg-dark-grey text-white font-semibold rounded-lg hover:bg-opacity-90 transition"
            >
              Продължете с пазаруването
            </Link>
          </div>
        ) : (
          <>
            <div className="space-y-3 mb-6">
              {cart.map((item, index) => (
                <div
                  key={index}
                  className="flex items-start gap-3 p-4 bg-white border border-gray-200 rounded-lg"
                >
                  {/* Product Image */}
                  <div className="w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-gray-100">
                    {item.image ? (
                      <img
                        src={`/images/products/${item.image}`}
                        alt={item.name}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          e.currentTarget.src = '/api/placeholder/300/400'
                        }}
                      />
                    ) : (
                      <div className="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-xs">Няма</span>
                      </div>
                    )}
                  </div>
                  {/* Product Details */}
                  <div className="flex-1 min-w-0">
                    <h3 className="text-base font-medium text-dark-grey mb-1">
                      {item.name}
                    </h3>
                    <div className="text-sm text-medium-grey space-y-1">
                      {item.size && <p>Размер: {item.size}</p>}
                      {item.color && <p>Цвят: {item.color}</p>}
                    </div>
                    <p className="text-base font-semibold text-dark-grey mt-2">
                      €{item.price ? item.price.toFixed(0) : '0'} ({convertToBGN(item.price)} лв)
                    </p>
                  </div>
                  <button
                    onClick={() => removeFromCart(index)}
                    className="ml-4 text-medium-grey hover:text-dark-grey transition flex-shrink-0"
                    aria-label="Премахни от количката"
                  >
                    <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>

            <div className="bg-white border-t border-gray-200 pt-6 mb-6 rounded-lg p-4">
              <div className="flex justify-between items-center mb-6">
                <span className="text-lg font-semibold text-dark-grey">Общо:</span>
                <span className="text-xl font-bold text-dark-grey">
                  €{total.toFixed(0)} ({convertToBGN(total)} лв)
                </span>
              </div>
              <div className="flex gap-3">
                <Link
                  href="/"
                  className="flex-1 px-6 py-3 border-2 border-dark-grey text-dark-grey font-semibold rounded-lg hover:bg-gray-50 transition text-center"
                >
                  Продължи пазаруването
                </Link>
                <button
                  onClick={() => router.push('/checkout')}
                  className="flex-1 px-6 py-3 bg-dark-grey text-white font-semibold rounded-lg hover:bg-opacity-90 transition"
                >
                  Поръчай сега
                </button>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Footer */}
      <footer className="bg-white border-t border-gray-200 mt-12">
        <div className="max-w-4xl 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>
  )
}

