import { useEffect, useState, useCallback } from 'react'
import { fetchProductDetail } from '../api/basicBasket'
import type { ProductDetail } from '../types/basicBasket'
import { formatDate, getCurrentUrl } from '../utils/formatters'
import StorePriceCard from './StorePriceCard'
import LoadingState from './LoadingState'
import ErrorState from './ErrorState'

interface ProductDetailViewProps {
  slug: string
  onBack: () => void
}

export default function ProductDetailView({ slug, onBack }: ProductDetailViewProps) {
  const [product, setProduct] = useState<ProductDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [shareToast, setShareToast] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await fetchProductDetail(slug)
      setProduct(res.data)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al cargar el producto.')
    } finally {
      setLoading(false)
    }
  }, [slug])

  useEffect(() => {
    load()
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }, [load])

  async function handleShare() {
    const url = getCurrentUrl()
    const title = product?.name ?? 'Canasta Básica'

    if (navigator.share) {
      try {
        await navigator.share({ title, url })
      } catch {
        // El usuario canceló, no hacer nada
      }
    } else {
      try {
        await navigator.clipboard.writeText(url)
        setShareToast(true)
        setTimeout(() => setShareToast(false), 2500)
      } catch {
        // Clipboard no disponible
      }
    }
  }

  if (loading) return <LoadingState message="Cargando producto…" />
  if (error) return <ErrorState message={error} onRetry={load} />
  if (!product) return null

  const sortedStores = [...product.stores].sort((a, b) => {
    if (a.price === null && b.price === null) return 0
    if (a.price === null) return 1
    if (b.price === null) return -1
    return parseFloat(a.price) - parseFloat(b.price)
  })

  return (
    <div>
      {/* Header del detalle */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-6">
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={onBack}
            className="flex items-center gap-1.5 text-sm text-[#87afa4] hover:text-[#3d3c3a] transition-colors font-medium"
            aria-label="Volver al listado"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            Volver
          </button>
          <h2 className="text-xl sm:text-2xl font-bold text-[#3d3c3a]">{product.name}</h2>
        </div>

        <div className="flex items-center gap-3 flex-shrink-0">
          {product.latest_checked_at && (
            <p className="text-sm text-gray-500 hidden sm:block">
              Última actualización: {formatDate(product.latest_checked_at)}
            </p>
          )}
          <button
            type="button"
            onClick={handleShare}
            className="relative px-4 py-2 text-sm font-semibold text-[#3d3c3a] border border-[#3d3c3a] rounded-lg hover:bg-[#3d3c3a] hover:text-white transition-colors focus:outline-none focus:ring-2 focus:ring-[#87afa4]"
          >
            Comparte
            {shareToast && (
              <span className="absolute -top-8 right-0 bg-[#3d3c3a] text-white text-xs px-2 py-1 rounded whitespace-nowrap">
                ¡URL copiada!
              </span>
            )}
          </button>
        </div>
      </div>

      {/* Fecha en mobile */}
      {product.latest_checked_at && (
        <p className="text-sm text-gray-500 sm:hidden mb-4">
          Última actualización: {formatDate(product.latest_checked_at)}
        </p>
      )}

      {/* Layout principal */}
      <div className="flex flex-col lg:flex-row gap-6 lg:gap-8">
        {/* Imagen del producto */}
        <div className="lg:w-80 xl:w-96 flex-shrink-0">
          <div className="aspect-square rounded-xl overflow-hidden bg-[#f4f5f6] border border-[#e5e7eb]">
            {product.image_url ? (
              <img
                src={product.image_url}
                alt={product.name}
                className="product-image w-full h-full"
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center" aria-hidden="true">
                <svg className="w-24 h-24 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={0.75}
                    d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"
                  />
                </svg>
              </div>
            )}
          </div>
          {product.category && (
            <p className="text-xs text-gray-500 mt-2 text-center">
              {product.category}
              {product.expected_unit ? ` · ${product.expected_unit}` : ''}
            </p>
          )}
        </div>

        {/* Lista de tiendas */}
        <div className="flex-1 min-w-0">
          <h3 className="text-base font-semibold text-[#3d3c3a] mb-3">
            Precios por tienda
            <span className="ml-2 text-sm font-normal text-gray-500">
              ({sortedStores.length} {sortedStores.length === 1 ? 'tienda' : 'tiendas'})
            </span>
          </h3>
          <ul className="flex flex-col gap-3">
            {sortedStores.map((storePrice) => (
              <li key={storePrice.store_id}>
                <StorePriceCard storePrice={storePrice} />
              </li>
            ))}
          </ul>
          {sortedStores.length === 0 && (
            <p className="text-sm text-gray-500 py-4">No hay precios disponibles para este producto.</p>
          )}
        </div>
      </div>
    </div>
  )
}

