import { useEffect, useState } from 'react'
import type { Product, Drone, CompleteDrone, KitBuild } from '../types'
import { useResolvedImage, resolveImageSync, resolveImage } from '../utils/imageCache'

function fmt(amount: number, currency: string) {
  return new Intl.NumberFormat('en', { style: 'currency', currency }).format(amount)
}

function kitTotal(kit: KitBuild): string {
  if (kit.parts.length === 0) return '—'
  const currency = kit.parts[0].price.currency
  const total = kit.parts.reduce((sum, p) => sum + p.price.amount, 0)
  return `~${fmt(total, currency)}`
}

interface Props {
  item: Product | Drone
  onEdit: () => void
  onRemove: () => void
}

export function ItemCard({ item, onEdit, onRemove }: Props) {
  const isDrone = 'buildType' in item
  const isKit = isDrone && (item as Drone).buildType === 'kit'

  const [hoverImg, setHoverImg] = useState<string | null>(null)
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 })

  // Preload part images into memCache so resolveImageSync works on hover
  useEffect(() => {
    if (!isKit) return
    for (const p of (item as KitBuild).parts) {
      if (p.image) resolveImage(p.image)
    }
  }, [item])

  const priceLabel = isKit
    ? kitTotal(item as KitBuild)
    : isDrone
      ? fmt((item as CompleteDrone).price.amount, (item as CompleteDrone).price.currency)
      : fmt((item as Product).price.amount, (item as Product).price.currency)

  const brand     = (item as CompleteDrone | Product).brand ?? null
  const category  = (item as Product).category ?? null
  const url       = (item as Product | CompleteDrone | KitBuild).url ?? null
  const thumbnail = useResolvedImage(item.image)

  return (
    <div
      className="flex gap-3 rounded-md border p-3"
      style={{ background: 'var(--color-bg1)', borderColor: 'var(--color-bg3)' }}
    >
      {/* Thumbnail */}
      {thumbnail ? (
        <img src={thumbnail} alt={item.name} className="h-16 w-16 shrink-0 rounded object-cover" />
      ) : (
        <div
          className="flex h-16 w-16 shrink-0 items-center justify-center rounded text-2xl"
          style={{ background: 'var(--color-bg2)' }}
        >
          {isDrone ? '🚁' : '📦'}
        </div>
      )}

      {/* Content */}
      <div className="flex min-w-0 flex-1 flex-col gap-1">
        <div className="flex items-start justify-between gap-2">
          <div className="min-w-0">
            <span className="font-medium" style={{ color: 'var(--color-fg)' }}>{item.name}</span>
            {brand && (
              <span className="ml-2 text-sm" style={{ color: 'var(--color-grey)' }}>{brand}</span>
            )}
          </div>
          <div className="flex shrink-0 items-center gap-2">
            {url && (
              <a href={url} target="_blank" rel="noopener noreferrer" className="text-xs underline" style={{ color: 'var(--color-cyan)' }}>
                Buy
              </a>
            )}
            <button onClick={onEdit} className="text-xs" style={{ color: 'var(--color-grey)' }} title="Edit">✎</button>
            <button onClick={onRemove} className="text-sm" style={{ color: 'var(--color-grey)' }} title="Remove">✕</button>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-1.5">
          {category && (
            <span className="rounded px-1.5 py-0.5 text-xs" style={{ background: 'var(--color-bg2)', color: 'var(--color-grey)' }}>
              {category}
            </span>
          )}
          {isDrone && (
            <span className="rounded px-1.5 py-0.5 text-xs" style={{ background: 'var(--color-bg2)', color: 'var(--color-blue)' }}>
              {(item as Drone).buildType}
            </span>
          )}
          <span className="text-sm font-medium" style={{ color: 'var(--color-yellow)' }}>{priceLabel}</span>
        </div>

        {item.note && (
          <p className="text-xs" style={{ color: 'var(--color-grey)' }}>{item.note}</p>
        )}

        {isKit && (item as KitBuild).parts.length > 0 && (
          <details className="mt-1">
            <summary className="cursor-pointer text-xs" style={{ color: 'var(--color-grey)' }}>
              {(item as KitBuild).parts.length} parts
            </summary>
            <ul className="mt-1 space-y-0.5 pl-2">
              {(item as KitBuild).parts.map(p => (
                <li
                  key={p.id}
                  className="flex items-center justify-between gap-2 text-xs"
                  style={{ color: 'var(--color-grey)', cursor: p.image ? 'default' : undefined }}
                  onMouseEnter={p.image ? e => { setHoverImg(resolveImageSync(p.image) ?? null); setMousePos({ x: e.clientX, y: e.clientY }) } : undefined}
                  onMouseMove={p.image ? e => setMousePos({ x: e.clientX, y: e.clientY }) : undefined}
                  onMouseLeave={p.image ? () => setHoverImg(null) : undefined}
                >
                  <div className="flex items-center gap-1.5 min-w-0">
                    <span className="shrink-0 rounded px-1.5 py-0.5" style={{ background: 'var(--color-bg2)', color: 'var(--color-grey)' }}>
                      {p.category}
                    </span>
                    <span className="truncate">{p.name}</span>
                    {p.image && <span className="shrink-0 text-xs" style={{ color: 'var(--color-bg3)' }}>▣</span>}
                  </div>
                  <div className="flex shrink-0 items-center gap-2">
                    <span>{fmt(p.price.amount, p.price.currency)}</span>
                    <button
                      onClick={() => navigator.clipboard.writeText(JSON.stringify(p))}
                      className="text-xs opacity-50 hover:opacity-100"
                      style={{ color: 'var(--color-grey)' }}
                      title="Copy part to clipboard"
                    >⎘</button>
                  </div>
                </li>
              ))}
            </ul>
          </details>
        )}
      </div>

      {/* Hover image preview */}
      {hoverImg && (
        <div
          className="pointer-events-none fixed z-50 rounded-lg border shadow-lg overflow-hidden"
          style={{
            left: mousePos.x + 16,
            top: mousePos.y + 16,
            borderColor: 'var(--color-bg3)',
            background: 'var(--color-bg1)',
          }}
        >
          <img src={hoverImg} alt="" className="block h-48 w-48 object-cover" />
        </div>
      )}
    </div>
  )
}
