'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'
import { ListingCard } from './ListingCard'
import { ListingThumb } from './ListingThumb'
import { MineralChip } from './MineralChip'
import { SatelliteMap } from './SatelliteMap'
import { Icon } from './Icon'
import { formatUsd, formatHa } from '@/lib/format'
import { COUNTRY_LABELS } from '@/lib/constants'
import {
  assetTypeLabel,
  stageLabel,
  modalityLabel,
  primaryCommodity,
} from '@/lib/listing-view'
import type { ListingWithRelations } from '@/lib/listings'
import type { MapPin } from '@/lib/map-pin'

type View = 'grid' | 'list' | 'map'

function ListRow({ listing }: { listing: ListingWithRelations }) {
  const primary = primaryCommodity(listing)
  return (
    <Link
      href={`/marketplace/${listing.slug}`}
      className="card list-row"
      style={{ display: 'grid', gridTemplateColumns: '200px 1fr 200px', alignItems: 'stretch' }}
    >
      <ListingThumb listing={listing} height={132} sizes="200px" />
      <div style={{ padding: '14px 18px', borderRight: '1px solid var(--line-softer)' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
          {primary && <MineralChip commodity={primary} size="sm" />}
          {listing.verified && (
            <span className="mono" style={{ fontSize: 9.5, padding: '2px 6px', background: 'var(--accent)', color: '#fff', letterSpacing: '0.08em' }}>
              ✓ VERIF
            </span>
          )}
          <span className="mono uppercase-wide" style={{ fontSize: 9.5, color: 'var(--muted)' }}>
            {assetTypeLabel(listing.assetType)}
          </span>
        </div>
        <div className="display" style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.2 }}>{listing.title}</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 6 }}>
          {[listing.city, listing.region, COUNTRY_LABELS[listing.country] ?? listing.country].filter(Boolean).join(' · ')}
          {' · '}{formatHa(listing.surfaceHa)} · {stageLabel(listing.stage) ?? '—'}
        </div>
        <div style={{ marginTop: 8, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
          {listing.description}
        </div>
      </div>
      <div style={{ padding: '14px 18px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div style={{ textAlign: 'right' }}>
          <div className="mono uppercase-wide" style={{ fontSize: 9.5, color: 'var(--muted)' }}>{modalityLabel(listing.dealTypes)}</div>
          <div className="display" style={{ fontSize: 20, fontWeight: 600 }}>{formatUsd(listing.priceUsd)}</div>
        </div>
        <span className="btn xs ghost" style={{ border: '1px solid var(--line-soft)' }}>
          Ver ficha <Icon name="arrow-right" size={10} />
        </span>
      </div>
    </Link>
  )
}

export function CatalogResults({
  listings,
  pins,
}: {
  listings: ListingWithRelations[]
  pins: MapPin[]
}) {
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()
  const [view, setView] = useState<View>('grid')

  const totalHa = listings.reduce((s, l) => s + (l.surfaceHa ?? 0), 0)
  const sort = params.get('orden') ?? 'recientes'

  function setSort(value: string) {
    const next = new URLSearchParams(params.toString())
    if (value === 'recientes') next.delete('orden')
    else next.set('orden', value)
    router.push(`${pathname}?${next.toString()}`)
  }

  const ViewBtn = ({ v, icon }: { v: View; icon: 'grid' | 'list' | 'map' }) => (
    <button
      onClick={() => setView(v)}
      style={{
        padding: '7px 10px',
        background: view === v ? 'var(--ink)' : 'transparent',
        color: view === v ? 'var(--bg-elev)' : 'var(--ink)',
        border: 0,
        display: 'flex',
        alignItems: 'center',
      }}
      aria-label={v}
    >
      <Icon name={icon} size={14} />
    </button>
  )

  return (
    <div>
      {/* Barra de resultados */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 16 }}>
        <div className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>
          <b style={{ color: 'var(--ink)' }}>{listings.length}</b> activos · {formatHa(totalHa)} totales
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <span className="mono uppercase-wide" style={{ fontSize: 10, color: 'var(--muted)' }}>Ordenar</span>
          <select value={sort} onChange={(e) => setSort(e.target.value)} className="input" style={{ height: 32, width: 180, fontSize: 12 }}>
            <option value="recientes">Más recientes</option>
            <option value="precio_asc">Precio ↑</option>
            <option value="precio_desc">Precio ↓</option>
          </select>
          <div style={{ display: 'flex', border: '1px solid var(--line)' }}>
            <ViewBtn v="grid" icon="grid" />
            <ViewBtn v="list" icon="list" />
            <ViewBtn v="map" icon="map" />
          </div>
        </div>
      </div>

      {listings.length === 0 ? (
        <div style={{ padding: 48, textAlign: 'center', border: '1px dashed var(--line-soft)' }}>
          <div className="display" style={{ fontSize: 18, fontWeight: 600 }}>Sin resultados</div>
          <div style={{ color: 'var(--muted)', marginTop: 6, fontSize: 13 }}>Ajusta los filtros para ampliar la búsqueda.</div>
        </div>
      ) : view === 'map' ? (
        <div style={{ border: '1px solid var(--line-soft)' }}>
          <SatelliteMap pins={pins} height={680} />
        </div>
      ) : view === 'list' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {listings.map((l) => (
            <ListRow key={l.id} listing={l} />
          ))}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 18 }}>
          {listings.map((l, i) => (
            <ListingCard key={l.id} listing={l} priority={i < 3} />
          ))}
        </div>
      )}
    </div>
  )
}
