import Link from 'next/link'
import { notFound } from 'next/navigation'
import { getListingBySlug, getListings } from '@/lib/listings'
import { toMapPins } from '@/lib/map-pin'
import { formatUsd, formatHa } from '@/lib/format'
import { COUNTRY_LABELS } from '@/lib/constants'
import {
  refCode,
  assetTypeLabel,
  modalityLabel,
  primaryCommodity,
  secondaryCommodities,
  stageLabel,
  stageCode,
} from '@/lib/listing-view'
import { ListingThumb } from '@/components/terrano/ListingThumb'
import { ListingCard } from '@/components/terrano/ListingCard'
import { MineralChip } from '@/components/terrano/MineralChip'
import { DetailTabs } from '@/components/terrano/DetailTabs'
import { ContactPublisher } from '@/components/terrano/ContactPublisher'
import { SectionHeader } from '@/components/terrano/SectionHeader'
import { Icon } from '@/components/terrano/Icon'

export const dynamic = 'force-dynamic'

function DarkRow({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '8px 0', borderBottom: '1px solid rgba(255,255,255,0.08)', gap: 12 }}>
      <span className="mono uppercase-wide" style={{ fontSize: 9.5, color: 'var(--muted-2)', letterSpacing: '0.1em' }}>{label}</span>
      <span className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{value}</span>
    </div>
  )
}

export default async function ListingPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const [listing, all] = await Promise.all([
    getListingBySlug(slug),
    getListings({ verifiedOnly: false, sort: 'recientes' }),
  ])
  if (!listing) notFound()

  const primary = primaryCommodity(listing)
  const others = all.filter((l) => l.id !== listing.id)
  const pins = toMapPins([listing, ...others])
  const related = others.filter((l) => primaryCommodity(l) === primary).slice(0, 3)
  const country = COUNTRY_LABELS[listing.country] ?? listing.country
  const place = [listing.city, `Región de ${listing.region}`].filter(Boolean).join(', ')

  return (
    <div>
      {/* Breadcrumb */}
      <section className="bleed" style={{ padding: '20px 28px', borderBottom: '1px solid var(--line-softer)', background: 'var(--bg-elev)' }}>
        <div className="mono uppercase-wide" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.1em' }}>
          <Link href="/marketplace" style={{ textDecoration: 'underline' }}>← Volver a resultados</Link>
          {' / '}{listing.region}{' / '}
          <span style={{ color: 'var(--ink)' }}>{refCode(listing)}</span>
        </div>
      </section>

      {/* Header */}
      <section className="bleed" style={{ padding: '28px 28px 24px' }}>
        <div className="detail-head" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 32, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12, flexWrap: 'wrap' }}>
              {primary && <MineralChip commodity={primary} />}
              {secondaryCommodities(listing).map((c) => (
                <MineralChip key={c} commodity={c} size="sm" />
              ))}
              <span className="mono uppercase-wide" style={{ fontSize: 10.5, padding: '3px 8px', background: 'var(--bg-sunk)', color: 'var(--ink-2)' }}>
                {assetTypeLabel(listing.assetType)}
              </span>
              {listing.verified && (
                <span className="mono uppercase-wide" style={{ fontSize: 10.5, padding: '3px 8px', background: 'var(--accent)', color: '#fff', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <Icon name="verified" size={11} /> Empresa verificada
                </span>
              )}
            </div>
            <h1 className="display" style={{ fontSize: 'clamp(30px, 4.5vw, 50px)', fontWeight: 600, margin: 0, letterSpacing: '-0.035em', lineHeight: 1.04 }}>
              {listing.title}
            </h1>
            <div className="mono" style={{ marginTop: 14, fontSize: 12, color: 'var(--muted)' }}>
              <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{refCode(listing)}</span>
              <span style={{ margin: '0 10px', color: 'var(--line-soft)' }}>│</span>
              {place}, {country}
              {listing.lat != null && listing.lng != null && (
                <>
                  <span style={{ margin: '0 10px', color: 'var(--line-soft)' }}>│</span>
                  {listing.lat}° {listing.lng}°
                </>
              )}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono uppercase-wide" style={{ fontSize: 10.5, color: 'var(--muted)', letterSpacing: '0.1em' }}>{modalityLabel(listing.dealTypes)}</div>
            <div className="display" style={{ fontSize: 'clamp(28px, 4vw, 42px)', fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1 }}>{formatUsd(listing.priceUsd)}</div>
          </div>
        </div>
      </section>

      {/* Galería */}
      <section className="bleed">
        <div className="gallery" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 8, height: 420 }}>
          <ListingThumb listing={listing} height={420} sizes="(max-width: 900px) 100vw, 640px" label={`${listing.title}`} corner="VISTA · LUGAR" priority />
          <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 8 }}>
            {['Foto 02', 'Foto 03'].map((n) => (
              <Placeholder key={n} note={n} />
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 8 }}>
            <Placeholder note="Foto 04" />
            <Placeholder note="Solicitar" badge="bajo solicitud" />
          </div>
        </div>
      </section>

      {/* Tabs + sidebar */}
      <section className="bleed detail-body" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 40, paddingTop: 8 }}>
        <DetailTabs listing={listing} pins={pins} />
        <aside style={{ paddingTop: 36 }}>
          <ContactPublisher company={listing.sellerCompany ?? 'Publicador privado'} title={listing.title} email={listing.contactEmail} />
          <div style={{ marginTop: 20, background: 'var(--ink)', color: 'var(--bg-elev)', padding: 20 }}>
            <div className="mono uppercase-wide" style={{ fontSize: 10, color: 'var(--muted-2)', letterSpacing: '0.1em' }}>Snapshot</div>
            <DarkRow label="Mineral" value={primary ?? '—'} />
            <DarkRow label="Superficie" value={formatHa(listing.surfaceHa)} />
            <DarkRow label="Concesiones" value={listing.concessionCount?.toString() ?? '—'} />
            <DarkRow label="Etapa" value={stageLabel(listing.stage) ?? '—'} />
            <DarkRow label="Modalidad" value={modalityLabel(listing.dealTypes)} />
            <DarkRow label="País" value={country} />
          </div>
        </aside>
      </section>

      {/* Relacionados */}
      {related.length > 0 && (
        <section className="bleed" style={{ paddingTop: 64, paddingBottom: 32 }}>
          <SectionHeader kicker="Activos similares" title="Más activos del mismo mineral" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 18 }}>
            {related.map((l) => (
              <ListingCard key={l.id} listing={l} />
            ))}
          </div>
        </section>
      )}
    </div>
  )
}

function Placeholder({ note, badge }: { note: string; badge?: string }) {
  return (
    <div className="placeholder" style={{ width: '100%', height: '100%', position: 'relative' }}>
      {badge && (
        <div className="mono uppercase-wide" style={{ position: 'absolute', top: 8, right: 8, fontSize: 9, padding: '3px 6px', background: 'rgba(20,20,20,0.7)', color: '#f6f3ee' }}>
          {badge}
        </div>
      )}
      <div className="mono uppercase-wide" style={{ position: 'absolute', inset: 'auto 0 0 0', padding: '6px 10px', display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--muted)', borderTop: '1px solid var(--line-soft)', background: 'rgba(246,243,238,0.7)' }}>
        <span>{note}</span>
        <span>faena.jpg</span>
      </div>
    </div>
  )
}
