'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Icon, type IconName } from './Icon'
import {
  COMMODITIES,
  COMMODITY_LABELS,
  COMMODITY_SYMBOLS,
  COUNTRY_LABELS,
  DEAL_TYPES,
  DEAL_TYPE_LABELS,
} from '@/lib/constants'

const TABS: { key: string; label: string; icon: IconName; category?: string; href?: string }[] = [
  { key: 'activos', label: 'Activos', icon: 'pickaxe', category: 'ACTIVO' },
  { key: 'productos', label: 'Productos', icon: 'mountain', category: 'PRODUCTO' },
  { key: 'servicios', label: 'Servicios', icon: 'drill', category: 'SERVICIO' },
  { key: 'inversion', label: 'Inversión', icon: 'trend-up', href: '/inversionistas' },
]

const QUICK: { label: string; q: string }[] = [
  { label: 'Cobre', q: 'commodity=CU' },
  { label: 'Oro', q: 'commodity=AU' },
  { label: 'Litio', q: 'commodity=LI' },
  { label: 'Chile', q: 'pais=CL' },
  { label: 'Argentina', q: 'pais=AR' },
  { label: 'Verificados', q: 'verificados=1' },
]

export function SearchConsole({ resultCount }: { resultCount: number }) {
  const router = useRouter()
  const [tab, setTab] = useState('activos')
  const [commodity, setCommodity] = useState('')
  const [country, setCountry] = useState('')
  const [deal, setDeal] = useState('')

  function buscar() {
    const params = new URLSearchParams()
    const active = TABS.find((t) => t.key === tab)
    if (active?.category) params.set('tipo', active.category)
    if (commodity) params.set('commodity', commodity)
    if (country) params.set('pais', country)
    if (deal) params.set('negocio', deal)
    router.push(`/marketplace?${params.toString()}`)
  }

  const fieldStyle = {
    border: '1px solid var(--line-soft)',
    padding: '8px 12px',
    background: 'var(--bg-elev)',
  } as const
  const fieldLabel = 'mono uppercase-wide'
  const fieldLabelStyle = {
    fontSize: 9,
    color: 'var(--muted)',
    letterSpacing: '0.1em',
    marginBottom: 4,
  } as const
  const selectStyle = {
    width: '100%',
    border: 0,
    background: 'transparent',
    fontSize: 13,
    fontWeight: 500,
    appearance: 'none' as const,
    cursor: 'pointer',
  }

  return (
    <div style={{ border: '1px solid var(--line)', background: 'var(--bg-elev)', boxShadow: 'var(--sh-2)' }}>
      {/* Tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
        {TABS.map((t) => {
          const active = tab === t.key
          const onClick = () => (t.href ? router.push(t.href) : setTab(t.key))
          return (
            <button
              key={t.key}
              onClick={onClick}
              className="uppercase-wide"
              style={{
                padding: '13px 20px',
                fontSize: 12,
                fontWeight: 600,
                letterSpacing: '0.04em',
                borderRight: '1px solid var(--line-softer)',
                background: active ? 'var(--ink)' : 'transparent',
                color: active ? 'var(--bg-elev)' : 'var(--muted)',
                display: 'flex',
                alignItems: 'center',
                gap: 8,
              }}
            >
              <Icon name={t.icon} size={13} /> {t.label}
            </button>
          )
        })}
        <div
          className="mono uppercase-wide"
          style={{ marginLeft: 'auto', padding: '13px 16px', fontSize: 10, color: 'var(--muted)' }}
        >
          {resultCount} activos
        </div>
      </div>

      {/* Campos */}
      <div className="console-fields" style={{ padding: 18, display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr auto', gap: 12 }}>
        <div style={fieldStyle}>
          <div className={fieldLabel} style={fieldLabelStyle}>Mineral</div>
          <select value={commodity} onChange={(e) => setCommodity(e.target.value)} style={selectStyle}>
            <option value="">Todos los minerales</option>
            {COMMODITIES.map((c) => (
              <option key={c} value={c}>
                {COMMODITY_SYMBOLS[c]} — {COMMODITY_LABELS[c]}
              </option>
            ))}
          </select>
        </div>
        <div style={fieldStyle}>
          <div className={fieldLabel} style={fieldLabelStyle}>País</div>
          <select value={country} onChange={(e) => setCountry(e.target.value)} style={selectStyle}>
            <option value="">Todos</option>
            {Object.entries(COUNTRY_LABELS).map(([k, v]) => (
              <option key={k} value={k}>{v}</option>
            ))}
          </select>
        </div>
        <div style={fieldStyle}>
          <div className={fieldLabel} style={fieldLabelStyle}>Modalidad</div>
          <select value={deal} onChange={(e) => setDeal(e.target.value)} style={selectStyle}>
            <option value="">Todas</option>
            {DEAL_TYPES.map((d) => (
              <option key={d} value={d}>{DEAL_TYPE_LABELS[d]}</option>
            ))}
          </select>
        </div>
        <button onClick={buscar} className="btn accent" style={{ height: '100%', padding: '0 22px' }}>
          <Icon name="search" size={13} /> Buscar
        </button>
      </div>

      {/* Filtros rápidos */}
      <div style={{ padding: '12px 18px', borderTop: '1px solid var(--line-softer)', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
        <span className="mono uppercase-wide" style={{ fontSize: 10, color: 'var(--muted)' }}>Filtros rápidos</span>
        {QUICK.map((f) => (
          <button key={f.label} onClick={() => router.push(`/marketplace?${f.q}`)} className="pill" style={{ cursor: 'pointer' }}>
            {f.label}
          </button>
        ))}
      </div>
    </div>
  )
}
