'use client'

import { useRouter, useSearchParams, usePathname } from 'next/navigation'
import {
  COMMODITY_LABELS,
  COMMODITY_SYMBOLS,
  STAGES,
  STAGE_LABELS,
  DEAL_TYPES,
  DEAL_TYPE_LABELS,
  COUNTRY_LABELS,
  type Commodity,
  type Stage,
  type DealType,
} from '@/lib/constants'
import { mineralColor } from '@/lib/minerals'

export type FacetCounts = {
  commodity: Record<string, number>
  stage: Record<string, number>
  dealType: Record<string, number>
  country: Record<string, number>
  verified: number
  total: number
}

function FacetHeader({ children }: { children: React.ReactNode }) {
  return (
    <div
      className="mono uppercase-wide"
      style={{
        fontSize: 10,
        color: 'var(--muted)',
        letterSpacing: '0.1em',
        marginBottom: 10,
        paddingBottom: 8,
        borderBottom: '1px solid var(--line-softer)',
      }}
    >
      {children}
    </div>
  )
}

export function Facets({ counts }: { counts: FacetCounts }) {
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()

  function setParam(key: string, value: string | null) {
    const next = new URLSearchParams(params.toString())
    if (value === null || next.get(key) === value) next.delete(key)
    else next.set(key, value)
    router.push(`${pathname}?${next.toString()}`)
  }

  const Row = ({
    active,
    label,
    count,
    onClick,
  }: {
    active: boolean
    label: React.ReactNode
    count?: number
    onClick: () => void
  }) => (
    <button
      onClick={onClick}
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        padding: '5px 0',
        width: '100%',
        background: 'none',
        border: 0,
        textAlign: 'left',
        fontSize: 12.5,
        color: 'var(--ink)',
      }}
    >
      <span
        style={{
          width: 14,
          height: 14,
          border: '1px solid var(--line)',
          background: active ? 'var(--ink)' : 'transparent',
          color: '#fff',
          fontSize: 10,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexShrink: 0,
        }}
      >
        {active ? '✓' : ''}
      </span>
      <span style={{ flex: 1 }}>{label}</span>
      {count != null && (
        <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{count}</span>
      )}
    </button>
  )

  const cur = (k: string) => params.get(k)

  return (
    <aside
      className="facets"
      style={{ padding: 24, borderRight: '1px solid var(--line-soft)', background: 'var(--bg-elev)' }}
    >
      <div style={{ marginBottom: 24 }}>
        <FacetHeader>Mineral principal</FacetHeader>
        <Row active={!cur('commodity')} label="Todos los minerales" count={counts.total} onClick={() => setParam('commodity', null)} />
        {(Object.keys(COMMODITY_LABELS) as Commodity[]).map((k) => {
          const c = counts.commodity[k] ?? 0
          if (c === 0) return null
          return (
            <Row
              key={k}
              active={cur('commodity') === k}
              count={c}
              onClick={() => setParam('commodity', k)}
              label={
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 8, height: 8, background: mineralColor(k) }} />
                  {COMMODITY_LABELS[k]}{' '}
                  <span className="mono" style={{ color: 'var(--muted-2)' }}>· {COMMODITY_SYMBOLS[k]}</span>
                </span>
              }
            />
          )
        })}
      </div>

      <div style={{ marginBottom: 24 }}>
        <FacetHeader>Etapa del proyecto</FacetHeader>
        <Row active={!cur('etapa')} label="Todas las etapas" count={counts.total} onClick={() => setParam('etapa', null)} />
        {STAGES.map((k) => {
          const c = counts.stage[k] ?? 0
          if (c === 0) return null
          return (
            <Row key={k} active={cur('etapa') === k} count={c} label={STAGE_LABELS[k as Stage]} onClick={() => setParam('etapa', k)} />
          )
        })}
      </div>

      <div style={{ marginBottom: 24 }}>
        <FacetHeader>Modalidad</FacetHeader>
        <Row active={!cur('negocio')} label="Todas" count={counts.total} onClick={() => setParam('negocio', null)} />
        {DEAL_TYPES.map((k) => {
          const c = counts.dealType[k] ?? 0
          if (c === 0) return null
          return (
            <Row key={k} active={cur('negocio') === k} count={c} label={DEAL_TYPE_LABELS[k as DealType]} onClick={() => setParam('negocio', k)} />
          )
        })}
      </div>

      <div style={{ marginBottom: 24 }}>
        <FacetHeader>País</FacetHeader>
        <Row active={!cur('pais')} label="Todos" count={counts.total} onClick={() => setParam('pais', null)} />
        {Object.keys(counts.country).map((k) => {
          const c = counts.country[k] ?? 0
          if (c === 0) return null
          return (
            <Row key={k} active={cur('pais') === k} count={c} label={COUNTRY_LABELS[k] ?? k} onClick={() => setParam('pais', k)} />
          )
        })}
      </div>

      <div>
        <FacetHeader>Calidad</FacetHeader>
        <Row
          active={cur('verificados') === '1'}
          count={counts.verified}
          label="Solo empresas verificadas"
          onClick={() => setParam('verificados', cur('verificados') === '1' ? null : '1')}
        />
      </div>
    </aside>
  )
}
