'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useLocale, useTranslations } from 'next-intl'
import { ArrowLeft, ArrowRight, Phone, ShoppingBag } from 'lucide-react'
import api from '@/lib/api'
import type { Locale, EshopData, EshopProduct } from '@/types'
import { t as tl } from '@/types'

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'
function resolveImage(src?: string) {
  if (!src) return undefined
  if (src.startsWith('http://') || src.startsWith('https://') || src.startsWith('/')) return src
  return `${API_URL}/${src}`
}

const formatPrice = (price: number) => `HK$${price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`

const discount = (regular: number, member: number) => {
  if (!regular || regular <= member) return 0
  return Math.round(((regular - member) / regular) * 100)
}

function ProductCard({ product, locale }: { product: EshopProduct; locale: Locale }) {
  const name = tl(product.name, locale)
  const desc = product.description ? tl(product.description, locale) : ''
  const img = resolveImage(product.image)
  const pct = discount(product.regularPrice, product.memberPrice)

  return (
    <div className="group bg-white rounded-sm shadow-sm overflow-hidden hover:shadow-lg transition-shadow duration-300">
      <div className="relative aspect-square bg-gray-50 flex items-center justify-center overflow-hidden">
        {img ? (
          <div
            className="absolute inset-0 bg-cover bg-center group-hover:scale-105 transition-transform duration-500"
            style={{ backgroundImage: `url('${img}')` }}
          />
        ) : (
          <ShoppingBag className="h-16 w-16 text-gray-300" />
        )}
        {pct > 0 && (
          <span className="absolute top-3 right-3 bg-red-500 text-white text-xs font-bold px-2.5 py-1 rounded-full shadow">
            -{pct}%
          </span>
        )}
      </div>

      <div className="p-5">
        {product.brand && (
          <p className="text-xs font-semibold text-primary-600 uppercase tracking-wide mb-1">
            {product.brand}
          </p>
        )}
        <h3 className="text-base font-bold text-secondary-900 mb-1 line-clamp-2 leading-snug">
          {name}
        </h3>
        {desc && <p className="text-sm text-secondary-500 line-clamp-2 mb-3">{desc}</p>}

        <div className="flex items-baseline gap-2.5 mt-auto">
          <span className="text-lg font-bold text-accent-gold">
            {formatPrice(product.memberPrice)}
          </span>
          {product.regularPrice > product.memberPrice && (
            <span className="text-sm text-secondary-400 line-through">
              {formatPrice(product.regularPrice)}
            </span>
          )}
        </div>
      </div>
    </div>
  )
}

export default function EshopPage() {
  const locale = useLocale() as Locale
  const t = useTranslations('services')
  const lp = (path: string) => `/${locale}${path}`
  const [data, setData] = useState<EshopData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.getEshop()
      .then(setData)
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="w-10 h-10 border-4 border-primary-200 border-t-primary-600 rounded-full animate-spin" />
      </div>
    )
  }

  const heroTitle = data ? tl(data.heroTitle, locale) : ''
  const heroSubtitle = data ? tl(data.heroSubtitle, locale) : ''
  const heroImage = resolveImage(data?.heroImage)

  const banner = data?.memberBanner
  const bannerTitle = banner ? tl(banner.title, locale) : ''
  const bannerDesc = banner ? tl(banner.description, locale) : ''
  const bannerCtaText = banner ? tl(banner.ctaText, locale) : ''
  const bannerCtaLink = banner?.ctaLink || ''
  const bannerImage = resolveImage(banner?.image)

  const products = (data?.products ?? []).filter(p => p.isActive)
  const hotline = data?.hotline || ''

  return (
    <div>
      {/* Hero */}
      <section className="relative min-h-[calc(100dvh-4rem)] lg:min-h-[calc(100dvh-100px)] flex items-end bg-secondary-950 overflow-hidden">
        {heroImage && (
          <>
            <div
              className="absolute inset-0 bg-cover bg-center"
              style={{ backgroundImage: `url('${heroImage}')` }}
            />
            <div className="absolute inset-0 bg-secondary-950/60" />
          </>
        )}
        <div className="relative z-10 max-w-7xl mx-auto container-padding pb-16 md:pb-24 pt-32 w-full text-white">
          <Link
            href={lp('/services')}
            className="inline-flex items-center text-sm font-semibold mb-8 transition-colors text-white/80 hover:text-white"
          >
            <ArrowLeft className="mr-1.5 h-4 w-4" />
            {t('backToServices')}
          </Link>
          <div className="max-w-3xl">
            <span className="section-label !text-white/70">
              {t('eshop.label')}
            </span>
            <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold mt-3 mb-6 tracking-tight text-white">
              {heroTitle}
            </h1>
            <p className="text-xl leading-relaxed text-white/70">
              {heroSubtitle}
            </p>
          </div>
        </div>
      </section>

      {/* Member Banner */}
      {bannerTitle && (
        <section className="bg-secondary-950 py-14 md:py-16">
          <div className="max-w-7xl mx-auto container-padding">
            <div className="flex flex-col md:flex-row items-center gap-8 md:gap-12">
              {bannerImage && (
                <div className="w-32 h-32 md:w-40 md:h-40 rounded-sm overflow-hidden flex-shrink-0 bg-white/10">
                  <div
                    className="w-full h-full bg-cover bg-center"
                    style={{ backgroundImage: `url('${bannerImage}')` }}
                  />
                </div>
              )}
              <div className="flex-1 text-center md:text-left">
                <h2 className="text-2xl md:text-3xl font-bold text-white mb-3">{bannerTitle}</h2>
                <p className="text-white/70 leading-relaxed mb-6 max-w-2xl">{bannerDesc}</p>
                {bannerCtaText && (
                  <a
                    href={bannerCtaLink}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="btn btn-accent inline-flex items-center"
                  >
                    {bannerCtaText}
                    <ArrowRight className="ml-2 h-5 w-5" />
                  </a>
                )}
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Products Grid */}
      <section className="section-padding bg-gray-50">
        <div className="max-w-7xl mx-auto container-padding">
          {products.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {products.map((product, idx) => (
                <ProductCard key={idx} product={product} locale={locale} />
              ))}
            </div>
          ) : (
            <div className="text-center py-20">
              <ShoppingBag className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <p className="text-secondary-500 text-lg">
                {t('eshop.comingSoon')}
              </p>
            </div>
          )}
        </div>
      </section>

      {/* Hotline */}
      {hotline && <section className="py-14 bg-white border-t border-gray-100">
        <div className="max-w-7xl mx-auto container-padding text-center">
          <div className="flex flex-col items-center gap-3">
            <div className="w-12 h-12 bg-primary-100 rounded-xl flex items-center justify-center">
              <Phone className="h-6 w-6 text-primary-600" />
            </div>
            <p className="text-secondary-500 text-sm">
              {t('eshop.hotlineText')}
            </p>
            <a href={`tel:${hotline.replace(/[^+\d]/g, '')}`} className="text-2xl font-bold text-secondary-900 hover:text-primary-600 transition-colors">
              {hotline}
            </a>
          </div>
        </div>
      </section>}

    </div>
  )
}
