import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { MapPin, Users, Clock, Briefcase, Search, X } from 'lucide-react'
import { JobsAPI } from '../api'
import { useTenantCtx } from '../context/TenantContext'

// ── Helpers ───────────────────────────────────────────────────────────────────

function timeAgo(s: string) {
  const diff = Date.now() - new Date(s).getTime()
  const days = Math.floor(diff / 86400000)
  if (days === 0) return 'Hoje'
  if (days === 1) return 'Ontem'
  if (days < 7)  return `${days}d atrás`
  if (days < 30) return `${Math.floor(days / 7)}sem atrás`
  return new Date(s).toLocaleDateString('pt-BR')
}

function fmtSalary(min: number | null, max: number | null, hide: boolean) {
  if (hide || (!min && !max)) return 'A combinar'
  const fmt = (v: number) => `R$ ${Number(v).toLocaleString('pt-BR', { maximumFractionDigits: 0 })}`
  if (min && max) return `${fmt(min)} – ${fmt(max)}`
  if (min)        return `A partir de ${fmt(min)}`
  return `Até ${fmt(max!)}`
}

const WORK_MODE_COLORS: Record<string, string> = {
  remoto:     'bg-emerald-500/15 text-emerald-400 border-emerald-500/20',
  hibrido:    'bg-blue-500/15 text-blue-400 border-blue-500/20',
  presencial: 'bg-amber-500/15 text-amber-400 border-amber-500/20',
}
const WORK_MODE_LABELS: Record<string, string> = {
  remoto: 'Remoto', hibrido: 'Híbrido', presencial: 'Presencial',
}
const JOB_TYPE_LABELS: Record<string, string> = {
  clt: 'CLT', pj: 'PJ', freelance: 'Freelance', estagio: 'Estágio', temporario: 'Temporário',
}

// ── Job Card ──────────────────────────────────────────────────────────────────

function JobCard({ job }: { job: any }) {
  const tenant = useTenantCtx()
  return (
    <Link to={`/vagas/${job.id}`}
      className="block bg-slate-900 border border-slate-800 hover:border-slate-700 rounded-2xl p-5 transition-all hover:-translate-y-0.5 hover:shadow-xl hover:shadow-black/20 group">
      <div className="flex items-start justify-between gap-3 mb-3">
        <h3 className="font-black text-white text-base group-hover:text-amber-400 transition-colors leading-tight">{job.title}</h3>
        <span className={`text-[10px] font-black px-2 py-0.5 rounded border shrink-0 ${WORK_MODE_COLORS[job.work_mode] || 'bg-slate-700 text-slate-400 border-slate-600'}`}>
          {WORK_MODE_LABELS[job.work_mode] || job.work_mode}
        </span>
      </div>

      <div className="flex flex-wrap gap-2 mb-3">
        <span className="text-[10px] font-bold px-2 py-0.5 rounded bg-slate-800 border border-slate-700 text-slate-400">
          {JOB_TYPE_LABELS[job.job_type] || job.job_type}
        </span>
        {job.category && (
          <span className="text-[10px] font-bold px-2 py-0.5 rounded bg-slate-800 border border-slate-700 text-slate-400">
            {job.category}
          </span>
        )}
      </div>

      <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-500 mb-4">
        {job.location && (
          <span className="flex items-center gap-1"><MapPin size={11} /> {job.location}</span>
        )}
        <span className="flex items-center gap-1"><Clock size={11} /> {timeAgo(job.published_at)}</span>
        <span className="flex items-center gap-1"><Users size={11} /> {job.applicants_count} candidato{job.applicants_count !== 1 ? 's' : ''}</span>
      </div>

      <div className="flex items-center justify-between">
        <p className="text-sm font-black" style={{ color: tenant.primary_color }}>
          {fmtSalary(job.salary_min, job.salary_max, job.salary_hide)}
        </p>
        <span className="text-xs font-black text-slate-400 group-hover:text-white transition-colors">
          Ver vaga →
        </span>
      </div>
    </Link>
  )
}

// ── Main Page ─────────────────────────────────────────────────────────────────

const WORK_MODES = ['remoto', 'hibrido', 'presencial']
const JOB_TYPES  = ['clt', 'pj', 'freelance', 'estagio', 'temporario']

export default function VagasListPage() {
  const tenant = useTenantCtx()
  const [jobs, setJobs]     = useState<any[]>([])
  const [total, setTotal]   = useState(0)
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [modeFilter, setModeFilter] = useState('')
  const [typeFilter, setTypeFilter] = useState('')
  const [offset, setOffset] = useState(0)
  const PER_PAGE = 12

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const res = await JobsAPI.list({
        search: search || undefined,
        work_mode: modeFilter || undefined,
        job_type: typeFilter || undefined,
        limit: PER_PAGE,
        offset,
      })
      setJobs(res.jobs || [])
      setTotal(res.total || 0)
    } catch {
      setJobs([])
    } finally {
      setLoading(false)
    }
  }, [search, modeFilter, typeFilter, offset])

  useEffect(() => {
    const t = setTimeout(load, 300)
    return () => clearTimeout(t)
  }, [load])

  // Reset offset on filter change
  useEffect(() => { setOffset(0) }, [search, modeFilter, typeFilter])

  function clearFilters() {
    setSearch('')
    setModeFilter('')
    setTypeFilter('')
  }
  const hasFilter = search || modeFilter || typeFilter

  return (
    <div className="min-h-screen bg-black pt-16">
      {/* Hero */}
      <section className="py-12 bg-gradient-to-b from-slate-950 to-black border-b border-slate-900">
        <div className="max-w-4xl mx-auto px-4 text-center">
          <div className="inline-flex items-center gap-2 text-xs font-black uppercase tracking-widest text-slate-400 bg-white/5 border border-white/10 px-3 py-1.5 rounded-full mb-4">
            <Briefcase size={12} style={{ color: tenant.primary_color }} /> Oportunidades
          </div>
          <h1 className="text-4xl sm:text-5xl font-black text-white tracking-tighter mb-3">Vagas de Emprego</h1>
          <p className="text-slate-400 text-lg mb-8">Encontre sua próxima oportunidade.</p>

          {/* Search bar */}
          <div className="relative max-w-xl mx-auto">
            <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" />
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Buscar por cargo, área, empresa..."
              className="w-full pl-11 pr-4 py-3.5 bg-slate-900 border border-slate-800 rounded-2xl text-sm text-white focus:outline-none focus:border-amber-500/50 placeholder:text-slate-600"
            />
            {search && (
              <button onClick={() => setSearch('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 hover:text-white">
                <X size={16} />
              </button>
            )}
          </div>
        </div>
      </section>

      <div className="max-w-6xl mx-auto px-4 py-10">
        {/* Filters */}
        <div className="flex flex-wrap items-center gap-3 mb-8">
          <p className="text-xs font-black text-slate-500 uppercase tracking-wider">Filtrar:</p>

          {/* Work mode chips */}
          {WORK_MODES.map(m => (
            <button key={m}
              onClick={() => setModeFilter(modeFilter === m ? '' : m)}
              className={`text-xs font-black px-3 py-1.5 rounded-xl border transition-all ${
                modeFilter === m
                  ? WORK_MODE_COLORS[m]
                  : 'border-slate-800 text-slate-500 hover:text-slate-300 hover:border-slate-700'
              }`}>
              {WORK_MODE_LABELS[m]}
            </button>
          ))}

          <div className="w-px h-4 bg-slate-800" />

          {/* Job type chips */}
          {JOB_TYPES.map(t => (
            <button key={t}
              onClick={() => setTypeFilter(typeFilter === t ? '' : t)}
              className={`text-xs font-black px-3 py-1.5 rounded-xl border transition-all ${
                typeFilter === t
                  ? 'bg-slate-700 text-white border-slate-600'
                  : 'border-slate-800 text-slate-500 hover:text-slate-300 hover:border-slate-700'
              }`}>
              {JOB_TYPE_LABELS[t]}
            </button>
          ))}

          {hasFilter && (
            <button onClick={clearFilters} className="text-xs font-bold text-slate-500 hover:text-rose-400 flex items-center gap-1 ml-auto">
              <X size={12} /> Limpar
            </button>
          )}
        </div>

        {/* Count */}
        <div className="flex items-center justify-between mb-6">
          <p className="text-slate-500 text-sm">
            {loading ? '…' : `${total} vaga${total !== 1 ? 's' : ''} encontrada${total !== 1 ? 's' : ''}`}
          </p>
        </div>

        {/* Grid */}
        {loading ? (
          <div className="flex justify-center py-24">
            <div className="w-8 h-8 border-2 border-t-transparent rounded-full animate-spin" style={{ borderColor: tenant.primary_color }} />
          </div>
        ) : jobs.length === 0 ? (
          <div className="text-center py-24">
            <Briefcase size={48} className="text-slate-700 mx-auto mb-4" />
            <p className="text-slate-600 italic">Nenhuma vaga encontrada com os filtros selecionados</p>
            {hasFilter && (
              <button onClick={clearFilters} className="mt-4 text-sm font-bold text-amber-400 hover:text-amber-300">
                Limpar filtros
              </button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            {jobs.map(j => <JobCard key={j.id} job={j} />)}
          </div>
        )}

        {/* Pagination */}
        {total > PER_PAGE && (
          <div className="flex items-center justify-center gap-3 mt-10">
            <button
              onClick={() => setOffset(Math.max(0, offset - PER_PAGE))}
              disabled={offset === 0}
              className="px-5 py-2 rounded-xl border border-slate-800 text-slate-400 hover:text-white text-sm font-bold disabled:opacity-30 transition-all">
              ← Anterior
            </button>
            <span className="text-slate-500 text-sm">
              Pág. {Math.floor(offset / PER_PAGE) + 1} de {Math.ceil(total / PER_PAGE)}
            </span>
            <button
              onClick={() => setOffset(offset + PER_PAGE)}
              disabled={offset + PER_PAGE >= total}
              className="px-5 py-2 rounded-xl border border-slate-800 text-slate-400 hover:text-white text-sm font-bold disabled:opacity-30 transition-all">
              Próxima →
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
