"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Bot } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { formatPrice } from "@/lib/utils"
import { productImage } from "@/lib/product-image"
import { CategoryControl } from "@/components/shop/shop-experience"
import { SketchLightbox } from "@/components/drops/sketch-lightbox"
import { CollaboratorPopup } from "@/components/drops/collaborator-popup"

export interface DropCollaborator {
  name: string
  role: string
  isAI: boolean
  photo: string | null
  universe: string
  background: string
  influences: string
}

export interface DropProduct {
  id: string
  name: string
  slug: string
  price: number
  images: string[]
  materials: string[]
  stock: number
  editionSize: number | null
}

export interface DropData {
  id: string
  slug: string
  name: string
  description: string | null
  releaseDate: string
  status: "UPCOMING" | "LIVE" | "SOLD_OUT"
  coverImage: string | null
  workshopVideoUrl: string | null
  stylist: DropCollaborator | null
  artist: DropCollaborator | null
  aiAgent: DropCollaborator | null
  electrician: DropCollaborator | null
  aiConcept: string | null
  sketches: string[]
  products: DropProduct[]
}

const STATUS_LABELS = {
  UPCOMING: { label: "Bientôt", variant: "upcoming" as const },
  LIVE: { label: "Live", variant: "drop" as const },
  SOLD_OUT: { label: "Sold Out", variant: "sold" as const },
}

/** Nom affiché dans le filtre : la partie après le tiret cadratin ("Capsule 002 — Aquatique" → "Aquatique"). */
function dropDisplayName(name: string): string {
  const parts = name.split(" — ")
  return parts.length > 1 ? parts[1] : name
}

export function DropsExperience({ drops }: { drops: DropData[] }) {
  const [index, setIndex] = useState(0)
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null)
  const [selectedCollab, setSelectedCollab] = useState<DropCollaborator | null>(null)
  const n = drops.length
  if (n === 0) return null
  const drop = drops[index % n]
  const status = STATUS_LABELS[drop.status]

  const values = drops.map((d) => ({ slug: d.slug, label: dropDisplayName(d.name) }))

  function move(dir: 1 | -1) {
    setIndex((i) => (i + dir + n) % n)
  }
  function select(slug: string) {
    const i = drops.findIndex((d) => d.slug === slug)
    if (i >= 0) setIndex(i)
  }

  return (
    <div>
      {/* En-tête deux colonnes : intro à gauche, filtre de drops à droite */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:items-center mb-16">
        <div>
          <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)] mb-3">
            Releases
          </p>
          <h1 className="text-4xl md:text-5xl font-heading font-bold uppercase tracking-tight text-[var(--text)]">
            Drops
          </h1>
        </div>
        <div className="flex lg:justify-end">
          <div className="w-full max-w-xs">
            <CategoryControl values={values} currentSlug={drop.slug} onSwipe={move} onSelect={select} />
          </div>
        </div>
      </div>

      {/* Détail du drop sélectionné */}
      <section className="border-t border-[var(--border)] pt-12">
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-4 mb-10">
          <div>
            <div className="flex items-center gap-3 mb-3">
              <Badge variant={status.variant}>{status.label}</Badge>
              <span className="font-mono text-xs text-[var(--text-muted)]">
                {new Date(drop.releaseDate).toLocaleDateString("fr-BE", {
                  day: "numeric",
                  month: "long",
                  year: "numeric",
                })}
              </span>
            </div>
            <h2 className="text-3xl md:text-4xl font-heading font-bold uppercase tracking-tight text-[var(--text)]">
              {drop.name}
            </h2>
            {drop.description && (
              <p className="mt-3 text-[var(--text-secondary)] max-w-lg">{drop.description}</p>
            )}
          </div>
          {drop.status === "LIVE" && (
            <Link
              href="/shop"
              className="font-mono text-xs uppercase tracking-widest text-[var(--text)] hover:text-[var(--accent)] transition-colors shrink-0"
            >
              Acheter maintenant →
            </Link>
          )}
        </div>

        {/* Image de couverture */}
        {drop.coverImage && (
          <div className="relative aspect-[21/9] w-full overflow-hidden bg-[var(--surface)] mb-16">
            <Image
              src={drop.coverImage}
              alt={drop.name}
              fill
              sizes="100vw"
              className="object-cover"
              priority
            />
          </div>
        )}

        {/* Collaboration : styliste × agent IA × graphiste × électronicien, côte à côte */}
        {(drop.stylist || drop.artist || drop.aiAgent || drop.electrician) && (
          <div className="mb-20">
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)] mb-8">
              La collaboration
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 sm:gap-8">
              {drop.stylist && <CollaboratorThumb collab={drop.stylist} onSelect={setSelectedCollab} />}
              {drop.aiAgent && <CollaboratorThumb collab={drop.aiAgent} onSelect={setSelectedCollab} />}
              {drop.artist && <CollaboratorThumb collab={drop.artist} onSelect={setSelectedCollab} />}
              {drop.electrician && <CollaboratorThumb collab={drop.electrician} onSelect={setSelectedCollab} />}
            </div>
            {selectedCollab && (
              <CollaboratorPopup collab={selectedCollab} onClose={() => setSelectedCollab(null)} />
            )}
          </div>
        )}

        {/* Croquis techniques générés par PROTO */}
        {drop.sketches.length > 0 && (
          <div className="mb-20">
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)] mb-6">
              Croquis — PROTO
            </p>
            <div className="flex gap-4 overflow-x-auto no-scrollbar snap-x snap-mandatory -mx-4 px-4 sm:mx-0 sm:px-0">
              {drop.sketches.map((src, i) => (
                <button
                  key={src}
                  type="button"
                  onClick={() => setLightboxIndex(i)}
                  className="relative h-[45vh] sm:h-[55vh] shrink-0 snap-start bg-[var(--surface)] border border-[var(--border)] overflow-hidden cursor-zoom-in group"
                  aria-label={`Agrandir le croquis ${i + 1}`}
                >
                  {/* Hauteur pilotée par le viewport (h-full sur le bouton
                      dimensionné en vh), largeur automatique selon le ratio
                      propre à chaque image — pas de recadrage forcé. Un
                      <img> classique plutôt que next/image : les croquis
                      n'ont pas tous le même ratio (4/5, 2/3, carré...), et
                      next/image fige un ratio unique via width/height, ce
                      qui figeait aussi la taille affichée d'une image à
                      l'autre au lieu de suivre sa vraie forme. */}
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={src}
                    alt={`Croquis PROTO — ${drop.name}`}
                    className="h-full w-auto object-contain p-2 transition-transform duration-300 group-hover:scale-[1.03]"
                  />
                </button>
              ))}
            </div>
            {lightboxIndex !== null && (
              <SketchLightbox
                key={lightboxIndex}
                srcs={drop.sketches}
                index={lightboxIndex}
                alt={`Croquis PROTO — ${drop.name}`}
                onClose={() => setLightboxIndex(null)}
                onNavigate={setLightboxIndex}
              />
            )}
          </div>
        )}

        {/* Immersion vidéo */}
        {drop.workshopVideoUrl && (
          <div className="mb-20">
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)] mb-6">
              Le défilé
            </p>
            <div className="relative aspect-video w-full overflow-hidden bg-[var(--surface)]">
              <iframe
                src={drop.workshopVideoUrl}
                title={`Défilé — ${drop.name}`}
                className="absolute inset-0 h-full w-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              />
            </div>
            <p className="mt-2 font-mono text-[10px] uppercase tracking-widest text-[var(--text-muted)]">
              Extrait du défilé — vidéo à titre d&rsquo;illustration
            </p>
          </div>
        )}

        {/* Galerie */}
        {drop.products.length > 0 && (
          <div>
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)] mb-6">
              La collection
            </p>
            <div className="flex gap-4 overflow-x-auto no-scrollbar snap-x snap-mandatory -mx-4 px-4 sm:mx-0 sm:px-0">
              {drop.products.map((p) => {
                const img = productImage(p.images, p.materials)
                return (
                  <Link
                    key={p.id}
                    href={`/shop/${p.slug}`}
                    className="group block w-[62vw] sm:w-[280px] shrink-0 snap-start"
                  >
                    <div className="relative aspect-[3/4] bg-[var(--surface)] border border-[var(--border)] group-hover:border-[var(--border-subtle)] overflow-hidden transition-colors mb-3">
                      {img ? (
                        <Image
                          src={img}
                          alt={p.name}
                          fill
                          sizes="(max-width: 640px) 62vw, 280px"
                          className="object-cover transition-transform duration-500 group-hover:scale-105"
                        />
                      ) : (
                        <div className="absolute inset-0 flex items-center justify-center">
                          <span className="font-mono text-xs text-[var(--text-muted)]">VALABEL</span>
                        </div>
                      )}
                      {p.editionSize && (
                        <div className="absolute top-3 left-3">
                          <Badge variant="accent">Édition {p.editionSize}</Badge>
                        </div>
                      )}
                    </div>
                    <p className="text-xs font-heading font-semibold uppercase tracking-wide text-[var(--text)]">
                      {p.name}
                    </p>
                    <p className="text-xs font-mono text-[var(--text-secondary)] mt-0.5">
                      {formatPrice(p.price)}
                    </p>
                  </Link>
                )
              })}
            </div>
          </div>
        )}
      </section>
    </div>
  )
}

function CollaboratorThumb({
  collab,
  onSelect,
}: {
  collab: DropCollaborator
  onSelect: (collab: DropCollaborator) => void
}) {
  return (
    <button
      type="button"
      onClick={() => onSelect(collab)}
      className="text-left group"
      aria-label={`${collab.name} — voir le profil`}
    >
      <div className="relative aspect-[4/5] bg-[var(--surface)] border border-[var(--border)] group-hover:border-[var(--border-subtle)] overflow-hidden transition-colors">
        {collab.photo ? (
          <Image
            src={collab.photo}
            alt={collab.name}
            fill
            sizes="(max-width: 640px) 33vw, 220px"
            className="object-cover transition-transform duration-300 group-hover:scale-[1.03]"
          />
        ) : collab.isAI ? (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 border border-[var(--accent)]/30 p-2 text-center">
            <Bot className="h-10 w-10 text-[var(--accent)]" strokeWidth={1} />
            <span className="font-mono text-[9px] uppercase tracking-widest text-[var(--text-muted)]">
              Agent logiciel
            </span>
          </div>
        ) : (
          <div className="absolute inset-0 flex items-center justify-center">
            <span className="font-mono text-xs text-[var(--text-muted)]">VALABEL</span>
          </div>
        )}
      </div>
      <div className="mt-2">
        <p className="text-xs font-heading font-semibold uppercase tracking-wide text-[var(--text)] truncate">
          {collab.name}
        </p>
        <p className="font-mono text-[10px] uppercase tracking-widest text-[var(--text-muted)] truncate">
          {collab.role}
        </p>
      </div>
    </button>
  )
}
