'use client'

import { useMemo, useState } from 'react'
import Link from 'next/link'
import { SatelliteMap } from './SatelliteMap'
import { Icon } from './Icon'
import { mineralColor } from '@/lib/minerals'
import { COMMODITY_SYMBOLS, type Commodity } from '@/lib/constants'
import type { MapPin } from '@/lib/map-pin'

export function AtlasExplorer({
  pins,
  height = 580,
  subtitle,
}: {
  pins: MapPin[]
  height?: number
  subtitle?: string
}) {
  const [hover, setHover] = useState<string | null>(null)
  const [mineral, setMineral] = useState<string>('all')

  const minerals = useMemo(() => {
    const set = new Set(pins.map((p) => p.mineral))
    return ['all', ...Array.from(set)]
  }, [pins])

  const filtered = mineral === 'all' ? pins : pins.filter((p) => p.mineral === mineral)

  return (
    <div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 12, flexWrap: 'wrap' }}>
        {minerals.map((k) => {
          const active = mineral === k
          return (
            <button
              key={k}
              onClick={() => setMineral(k)}
              className="pill"
              style={{
                background: active ? 'var(--ink)' : 'var(--bg-elev)',
                color: active ? 'var(--bg-elev)' : 'var(--ink)',
                borderColor: active ? 'var(--ink)' : 'var(--line-soft)',
                cursor: 'pointer',
              }}
            >
              {k === 'all' ? 'Todos' : (COMMODITY_SYMBOLS[k as Commodity] ?? k)}
            </button>
          )
        })}
      </div>

      <div
        className="atlas-grid"
        style={{
          border: '1px solid var(--line-soft)',
          display: 'grid',
          gridTemplateColumns: '1fr 360px',
          background: 'var(--bg-elev)',
        }}
      >
        <SatelliteMap pins={filtered} height={height} hoveredId={hover} onHover={setHover} />
        <div style={{ display: 'flex', flexDirection: 'column', height, borderLeft: '1px solid var(--line-soft)' }}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line-soft)' }}>
            <div className="mono uppercase-wide" style={{ fontSize: 9.5, color: 'var(--muted)', letterSpacing: '0.08em' }}>
              {filtered.length} activos visibles
            </div>
            <div className="display" style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>
              {subtitle ?? 'Activos mineros georreferenciados'}
            </div>
          </div>
          <div style={{ overflowY: 'auto', flex: 1 }}>
            {filtered.map((p) => (
              <Link
                key={p.id}
                href={`/marketplace/${p.slug}`}
                onMouseEnter={() => setHover(p.id)}
                onMouseLeave={() => setHover(null)}
                style={{
                  display: 'grid',
                  gridTemplateColumns: '34px 1fr auto',
                  gap: 12,
                  padding: '12px 18px',
                  borderBottom: '1px solid var(--line-softer)',
                  background: hover === p.id ? 'var(--bg-sunk)' : 'transparent',
                  transition: 'background .1s',
                  alignItems: 'center',
                }}
              >
                <span
                  className="mono"
                  style={{
                    width: 34,
                    height: 34,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    border: '1px solid var(--line-soft)',
                    background: 'var(--bg)',
                    fontSize: 11,
                    fontWeight: 700,
                    position: 'relative',
                  }}
                >
                  <span style={{ position: 'absolute', top: -1, right: -1, width: 7, height: 7, background: mineralColor(p.mineral) }} />
                  {COMMODITY_SYMBOLS[p.mineral as Commodity] ?? p.mineral}
                </span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                    <span style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {p.title}
                    </span>
                    {p.verified && <span className="mono" style={{ fontSize: 8.5, color: 'var(--accent)' }}>✓</span>}
                  </span>
                  <span className="mono" style={{ display: 'block', fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>
                    {p.haLabel} · {p.city || p.region}
                  </span>
                </span>
                <span style={{ textAlign: 'right' }}>
                  <span className="mono uppercase-wide" style={{ display: 'block', fontSize: 8.5, color: 'var(--muted)' }}>{p.modality}</span>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{p.priceLabel}</span>
                </span>
              </Link>
            ))}
            {filtered.length === 0 && (
              <div style={{ padding: 24, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>
                Sin activos para este mineral.
              </div>
            )}
          </div>
          <div style={{ padding: '10px 18px', borderTop: '1px solid var(--line-soft)' }}>
            <Link href="/marketplace" className="btn sm ghost" style={{ width: '100%', border: '1px solid var(--line-soft)' }}>
              <Icon name="grid" size={12} /> Ver catálogo completo
            </Link>
          </div>
        </div>
      </div>
    </div>
  )
}
