import { useState, useEffect, useCallback } from 'react';
import {
  Briefcase, Users, UserCheck, Tag,
  Plus, Edit2, Trash2, X,
  Eye, ToggleLeft, ToggleRight, Search, FileText,
  MapPin, Download, ArrowLeft,
} from 'lucide-react';
import { JobsService } from '../services/api';

// ── Types ─────────────────────────────────────────────────────────────────────

interface Job {
  id: number; title: string; description: string; requirements: string | null;
  benefits: string | null; location: string | null; work_mode: string;
  job_type: string; category: string | null; salary_min: number | null;
  salary_max: number | null; salary_hide: boolean; slots: number;
  active: boolean; published_at: string; expires_at: string | null;
  applicants_count: number;
}

interface Application {
  id: number; applicant_nome: string; applicant_cpf: string;
  applicant_email: string | null; applicant_phone: string | null;
  cover_letter: string | null; status: string; applied_at: string;
  admin_notes: string | null; about: string | null;
  experience: any[]; education: any[]; skills: any[];
  file_url: string | null; linkedin: string | null; portfolio: string | null;
}

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

function fmtDate(s: string | null) {
  if (!s) return '—';
  return new Date(s).toLocaleDateString('pt-BR');
}

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

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} dias atrás`;
  if (days < 30) return `${Math.floor(days / 7)} sem. atrás`;
  return fmtDate(s);
}

const WORK_MODE_LABELS: Record<string, string> = {
  presencial: 'Presencial', hibrido: 'Híbrido', remoto: 'Remoto',
};
const JOB_TYPE_LABELS: Record<string, string> = {
  clt: 'CLT', pj: 'PJ', freelance: 'Freelance', estagio: 'Estágio', temporario: 'Temporário',
};
const APP_STATUS_LABEL: Record<string, string> = {
  novo: 'Novo', em_analise: 'Em Análise', aprovado: 'Aprovado',
  reprovado: 'Reprovado', contratado: 'Contratado',
};
const APP_STATUS_COLOR: Record<string, string> = {
  novo: 'bg-slate-700 text-slate-300',
  em_analise: 'bg-blue-500/10 text-blue-400 border-blue-500/20',
  aprovado: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
  reprovado: 'bg-rose-500/10 text-rose-400 border-rose-500/20',
  contratado: 'bg-violet-500/10 text-violet-400 border-violet-500/20',
};

const WORK_MODE_COLOR: Record<string, string> = {
  presencial: 'bg-amber-500/10 text-amber-400 border-amber-500/20',
  hibrido: 'bg-blue-500/10 text-blue-400 border-blue-500/20',
  remoto: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
};

function Badge({ label, color }: { label: string; color: string }) {
  return (
    <span className={`text-[10px] font-black px-2 py-0.5 rounded border ${color}`}>{label}</span>
  );
}

// ── Job Modal ─────────────────────────────────────────────────────────────────

const EMPTY_JOB = {
  title: '', description: '', requirements: '', benefits: '', location: '',
  work_mode: 'presencial', job_type: 'clt', category: '',
  salary_min: '', salary_max: '', salary_hide: false,
  slots: 1, active: true, expires_at: '',
};

function JobModal({ job, onClose, onSaved }: { job: Job | null; onClose: () => void; onSaved: () => void }) {
  const [form, setForm] = useState<any>(job ? {
    ...job,
    salary_min: job.salary_min ?? '',
    salary_max: job.salary_max ?? '',
    expires_at: job.expires_at ? job.expires_at.slice(0, 10) : '',
    requirements: job.requirements || '',
    benefits: job.benefits || '',
    location: job.location || '',
    category: job.category || '',
  } : EMPTY_JOB);
  const [saving, setSaving] = useState(false);

  function f(key: string, val: any) {
    setForm((p: any) => ({ ...p, [key]: val }));
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const payload = {
        ...form,
        salary_min: form.salary_min === '' ? null : Number(form.salary_min),
        salary_max: form.salary_max === '' ? null : Number(form.salary_max),
        expires_at: form.expires_at || null,
      };
      if (job) await JobsService.update(job.id, payload);
      else     await JobsService.create(payload);
      onSaved(); onClose();
    } catch { alert('Erro ao salvar vaga'); }
    finally { setSaving(false); }
  }

  const inputCls = 'w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500';
  const labelCls = 'text-xs font-bold text-slate-400 uppercase tracking-wider';

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-2xl max-h-[92vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b border-slate-800 sticky top-0 bg-slate-900 z-10">
          <h3 className="text-lg font-black text-white">{job ? 'Editar Vaga' : 'Nova Vaga'}</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white"><X size={20} /></button>
        </div>

        <form onSubmit={submit} className="p-6 space-y-5">
          {/* Título */}
          <div>
            <label className={labelCls}>Título da Vaga *</label>
            <input required value={form.title} onChange={e => f('title', e.target.value)}
              placeholder="Ex: Desenvolvedor Full Stack" className={`mt-1 ${inputCls}`} />
          </div>

          {/* Modo + Tipo + Categoria */}
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className={labelCls}>Modo</label>
              <select value={form.work_mode} onChange={e => f('work_mode', e.target.value)} className={`mt-1 ${inputCls}`}>
                <option className="bg-slate-900 text-white" value="presencial">Presencial</option>
                <option className="bg-slate-900 text-white" value="hibrido">Híbrido</option>
                <option className="bg-slate-900 text-white" value="remoto">Remoto</option>
              </select>
            </div>
            <div>
              <label className={labelCls}>Contrato</label>
              <select value={form.job_type} onChange={e => f('job_type', e.target.value)} className={`mt-1 ${inputCls}`}>
                <option className="bg-slate-900 text-white" value="clt">CLT</option>
                <option className="bg-slate-900 text-white" value="pj">PJ</option>
                <option className="bg-slate-900 text-white" value="freelance">Freelance</option>
                <option className="bg-slate-900 text-white" value="estagio">Estágio</option>
                <option className="bg-slate-900 text-white" value="temporario">Temporário</option>
              </select>
            </div>
            <div>
              <label className={labelCls}>Categoria</label>
              <input value={form.category} onChange={e => f('category', e.target.value)}
                placeholder="Ex: TI, Saúde..." className={`mt-1 ${inputCls}`} />
            </div>
          </div>

          {/* Localização + Vagas + Expira */}
          <div className="grid grid-cols-3 gap-3">
            <div className="col-span-1">
              <label className={labelCls}>Localização</label>
              <input value={form.location} onChange={e => f('location', e.target.value)}
                placeholder="Cidade / UF" className={`mt-1 ${inputCls}`} />
            </div>
            <div>
              <label className={labelCls}>Nº de Vagas</label>
              <input type="number" min={1} value={form.slots} onChange={e => f('slots', +e.target.value)} className={`mt-1 ${inputCls}`} />
            </div>
            <div>
              <label className={labelCls}>Expira em</label>
              <input type="date" value={form.expires_at} onChange={e => f('expires_at', e.target.value)} className={`mt-1 ${inputCls}`} />
            </div>
          </div>

          {/* Salário */}
          <div className="grid grid-cols-3 gap-3 items-end">
            <div>
              <label className={labelCls}>Salário Mín (R$)</label>
              <input type="number" min={0} value={form.salary_min}
                onChange={e => f('salary_min', e.target.value)} disabled={form.salary_hide}
                placeholder="0,00" className={`mt-1 ${inputCls} disabled:opacity-40`} />
            </div>
            <div>
              <label className={labelCls}>Salário Máx (R$)</label>
              <input type="number" min={0} value={form.salary_max}
                onChange={e => f('salary_max', e.target.value)} disabled={form.salary_hide}
                placeholder="0,00" className={`mt-1 ${inputCls} disabled:opacity-40`} />
            </div>
            <label className="flex items-center gap-2 cursor-pointer pb-2">
              <input type="checkbox" checked={form.salary_hide} onChange={e => f('salary_hide', e.target.checked)} className="accent-cyan-500" />
              <span className="text-sm text-slate-300">A combinar</span>
            </label>
          </div>

          {/* Descrição */}
          <div>
            <label className={labelCls}>Descrição *</label>
            <textarea required rows={5} value={form.description}
              onChange={e => f('description', e.target.value)}
              placeholder="Descreva as responsabilidades e o dia a dia da função..."
              className={`mt-1 ${inputCls} resize-y`} />
          </div>

          {/* Requisitos */}
          <div>
            <label className={labelCls}>Requisitos</label>
            <textarea rows={3} value={form.requirements}
              onChange={e => f('requirements', e.target.value)}
              placeholder="Experiência, formação, habilidades exigidas..."
              className={`mt-1 ${inputCls} resize-y`} />
          </div>

          {/* Benefícios */}
          <div>
            <label className={labelCls}>Benefícios</label>
            <textarea rows={3} value={form.benefits}
              onChange={e => f('benefits', e.target.value)}
              placeholder="VT, VR, Plano de saúde, home office..."
              className={`mt-1 ${inputCls} resize-y`} />
          </div>

          {job && (
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={form.active} onChange={e => f('active', e.target.checked)} className="accent-cyan-500" />
              <span className="text-sm text-slate-300">Vaga ativa</span>
            </label>
          )}

          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="flex-1 py-2.5 rounded-xl border border-slate-700 text-slate-400 hover:text-white text-sm font-bold">
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              className="flex-1 py-2.5 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-black text-sm font-black disabled:opacity-50">
              {saving ? 'Salvando…' : job ? 'Atualizar Vaga' : 'Publicar Vaga'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Candidate Detail Modal ────────────────────────────────────────────────────

function CandidateModal({ app, onClose, onUpdated }: {
  app: Application; onClose: () => void; onUpdated: () => void;
}) {
  const [status, setStatus] = useState(app.status);
  const [notes, setNotes]   = useState(app.admin_notes || '');
  const [saving, setSaving] = useState(false);

  async function save() {
    setSaving(true);
    try {
      await JobsService.updateApplication(app.id, { status, admin_notes: notes });
      onUpdated(); onClose();
    } catch { alert('Erro ao atualizar'); }
    finally { setSaving(false); }
  }

  return (
    <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-end md:items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-t-3xl md:rounded-3xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b border-slate-800 sticky top-0 bg-slate-900 z-10">
          <div>
            <h3 className="text-lg font-black text-white">{app.applicant_nome}</h3>
            <p className="text-slate-500 text-xs mt-0.5">Candidatado em {fmtDate(app.applied_at)}</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white"><X size={20} /></button>
        </div>

        <div className="p-6 space-y-6">
          {/* Dados */}
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div><p className="text-slate-500 text-xs">CPF</p><p className="text-white font-mono">{app.applicant_cpf}</p></div>
            <div><p className="text-slate-500 text-xs">Telefone</p><p className="text-white">{app.applicant_phone || '—'}</p></div>
            <div><p className="text-slate-500 text-xs">Email</p><p className="text-white">{app.applicant_email || '—'}</p></div>
            {app.linkedin && <div><p className="text-slate-500 text-xs">LinkedIn</p><a href={app.linkedin} target="_blank" className="text-cyan-400 underline text-xs">Perfil</a></div>}
          </div>

          {/* Carta de apresentação */}
          {app.cover_letter && (
            <div>
              <p className="text-xs font-black text-slate-400 uppercase tracking-wider mb-2">Carta de Apresentação</p>
              <p className="text-slate-300 text-sm bg-slate-800/40 border border-slate-800 rounded-2xl p-4 whitespace-pre-line">{app.cover_letter}</p>
            </div>
          )}

          {/* Sobre */}
          {app.about && (
            <div>
              <p className="text-xs font-black text-slate-400 uppercase tracking-wider mb-2">Sobre o Candidato</p>
              <p className="text-slate-300 text-sm whitespace-pre-line">{app.about}</p>
            </div>
          )}

          {/* Experiências */}
          {app.experience?.length > 0 && (
            <div>
              <p className="text-xs font-black text-slate-400 uppercase tracking-wider mb-3">Experiências</p>
              <div className="space-y-3">
                {app.experience.map((e: any, i: number) => (
                  <div key={i} className="border-l-2 border-cyan-500/30 pl-4">
                    <p className="font-black text-white text-sm">{e.role} <span className="font-normal text-slate-400">@ {e.company}</span></p>
                    <p className="text-slate-500 text-xs">{e.start} – {e.current ? 'Atual' : e.end}</p>
                    {e.description && <p className="text-slate-400 text-xs mt-1">{e.description}</p>}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Formação */}
          {app.education?.length > 0 && (
            <div>
              <p className="text-xs font-black text-slate-400 uppercase tracking-wider mb-3">Formação</p>
              <div className="space-y-2">
                {app.education.map((e: any, i: number) => (
                  <div key={i} className="border-l-2 border-violet-500/30 pl-4">
                    <p className="font-black text-white text-sm">{e.degree} em {e.course}</p>
                    <p className="text-slate-500 text-xs">{e.institution} · {e.start} – {e.current ? 'Atual' : e.end}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Habilidades */}
          {app.skills?.length > 0 && (
            <div>
              <p className="text-xs font-black text-slate-400 uppercase tracking-wider mb-2">Habilidades</p>
              <div className="flex flex-wrap gap-2">
                {app.skills.map((s: any, i: number) => (
                  <span key={i} className="text-xs font-bold px-2.5 py-1 rounded-full bg-slate-800 border border-slate-700 text-slate-300">
                    {s.name} <span className="text-slate-500">· {s.level}</span>
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* PDF */}
          {app.file_url && (
            <a href={app.file_url} target="_blank" rel="noopener noreferrer"
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-slate-800 border border-slate-700 hover:border-cyan-500/30 text-slate-300 hover:text-white text-sm font-bold transition-all w-fit">
              <Download size={14} /> Baixar Currículo PDF
            </a>
          )}

          {/* Status + Notas */}
          <div className="space-y-3 pt-3 border-t border-slate-800">
            <div>
              <label className="text-xs font-black text-slate-400 uppercase tracking-wider block mb-2">Status</label>
              <div className="flex flex-wrap gap-2">
                {Object.entries(APP_STATUS_LABEL).map(([k, v]) => (
                  <button key={k} onClick={() => setStatus(k)}
                    className={`text-xs font-black px-3 py-1.5 rounded-lg border transition-all ${
                      status === k ? APP_STATUS_COLOR[k] : 'bg-slate-800 border-slate-700 text-slate-400 hover:text-white'
                    }`}>
                    {v}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="text-xs font-black text-slate-400 uppercase tracking-wider block mb-1">Notas Internas</label>
              <textarea rows={3} value={notes} onChange={e => setNotes(e.target.value)}
                placeholder="Observações internas sobre o candidato..."
                className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 resize-none" />
            </div>
            <button onClick={save} disabled={saving}
              className="w-full py-3 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm disabled:opacity-50">
              {saving ? 'Salvando…' : 'Salvar Status e Notas'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Applications Drawer ───────────────────────────────────────────────────────

function ApplicationsDrawer({ job, onClose }: { job: Job; onClose: () => void }) {
  const [apps, setApps]         = useState<Application[]>([]);
  const [loading, setLoading]   = useState(true);
  const [statusFilter, setFilter] = useState('');
  const [selected, setSelected] = useState<Application | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await JobsService.getApplications(job.id, { status: statusFilter || undefined });
      setApps(data || []);
    } catch { setApps([]); }
    finally { setLoading(false); }
  }, [job.id, statusFilter]);

  useEffect(() => { load(); }, [load]);

  return (
    <>
      <div className="fixed inset-0 bg-black/60 z-40" onClick={onClose} />
      <aside className="fixed right-0 top-0 h-full w-full max-w-xl bg-slate-900 border-l border-slate-800 z-50 flex flex-col shadow-2xl">
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <div>
            <h3 className="text-lg font-black text-white">{job.title}</h3>
            <p className="text-slate-500 text-xs mt-0.5">{apps.length} candidatos</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white"><X size={20} /></button>
        </div>

        {/* Status filter */}
        <div className="flex gap-1.5 p-4 border-b border-slate-800 flex-wrap">
          {['', ...Object.keys(APP_STATUS_LABEL)].map(s => (
            <button key={s || 'all'} onClick={() => setFilter(s)}
              className={`text-[10px] font-black px-2.5 py-1 rounded-lg border transition-all ${
                statusFilter === s
                  ? 'bg-cyan-500/10 border-cyan-500/30 text-cyan-400'
                  : 'border-slate-700 text-slate-500 hover:text-slate-300'
              }`}>
              {s ? APP_STATUS_LABEL[s] : 'Todos'}
            </button>
          ))}
        </div>

        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {loading && (
            <div className="flex justify-center py-12">
              <div className="w-7 h-7 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin" />
            </div>
          )}
          {!loading && apps.length === 0 && (
            <p className="text-slate-600 italic text-center py-12">Nenhum candidato</p>
          )}
          {apps.map(a => (
            <div key={a.id}
              onClick={() => setSelected(a)}
              className="bg-slate-800/40 border border-slate-800 hover:border-slate-700 rounded-2xl p-4 cursor-pointer transition-all hover:bg-slate-800/60">
              <div className="flex items-start justify-between gap-2">
                <div>
                  <p className="font-bold text-white text-sm">{a.applicant_nome}</p>
                  <p className="text-slate-500 text-xs font-mono">{a.applicant_cpf}</p>
                </div>
                <span className={`text-[10px] font-black px-2 py-0.5 rounded border shrink-0 ${APP_STATUS_COLOR[a.status]}`}>
                  {APP_STATUS_LABEL[a.status]}
                </span>
              </div>
              <p className="text-slate-500 text-xs mt-2">{timeAgo(a.applied_at)}</p>
              {a.cover_letter && (
                <p className="text-slate-500 text-xs mt-1 line-clamp-1 italic">"{a.cover_letter}"</p>
              )}
            </div>
          ))}
        </div>
      </aside>

      {selected && (
        <CandidateModal
          app={selected}
          onClose={() => setSelected(null)}
          onUpdated={load}
        />
      )}
    </>
  );
}

// ── Resumes Page ──────────────────────────────────────────────────────────────

function ResumesView({ onBack }: { onBack: () => void }) {
  const [resumes, setResumes]   = useState<any[]>([]);
  const [search, setSearch]     = useState('');
  const [loading, setLoading]   = useState(false);
  const [selected, setSelected] = useState<any | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await JobsService.searchResumes({ search: search || undefined, limit: 100 });
      setResumes(data || []);
    } catch { setResumes([]); }
    finally { setLoading(false); }
  }, [search]);

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

  function fmtCpf(cpf: string) {
    return cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <button onClick={onBack} className="text-slate-400 hover:text-white">
          <ArrowLeft size={20} />
        </button>
        <h3 className="text-2xl font-black text-white">Banco de Currículos</h3>
      </div>

      <div className="relative">
        <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
        <input
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Buscar por nome ou CPF..."
          className="w-full pl-9 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-sm text-white focus:outline-none focus:border-cyan-500"
        />
      </div>

      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl overflow-hidden">
        {loading ? (
          <div className="flex justify-center py-12">
            <div className="w-7 h-7 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-800">
                {['Nome', 'CPF', 'E-mail', 'Telefone', 'Candidaturas', 'Atualizado', ''].map(h => (
                  <th key={h} className="text-left px-5 py-4 text-[10px] font-black uppercase tracking-widest text-slate-500 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {resumes.length === 0 && (
                <tr><td colSpan={7} className="text-center py-12 text-slate-600 italic">Nenhum currículo encontrado</td></tr>
              )}
              {resumes.map(r => (
                <tr key={r.id} className="border-b border-slate-800/50 hover:bg-slate-800/30 transition-colors">
                  <td className="px-5 py-3.5 font-bold text-white">{r.user_nome}</td>
                  <td className="px-5 py-3.5 text-slate-400 font-mono text-xs">{fmtCpf(r.user_cpf)}</td>
                  <td className="px-5 py-3.5 text-slate-400 text-xs">{r.email || '—'}</td>
                  <td className="px-5 py-3.5 text-slate-400 text-xs">{r.phone || '—'}</td>
                  <td className="px-5 py-3.5 text-center">
                    <span className="text-xs font-black text-cyan-400 bg-cyan-500/10 px-2 py-0.5 rounded">{r.applications_count}</span>
                  </td>
                  <td className="px-5 py-3.5 text-slate-500 text-xs">{fmtDate(r.updated_at)}</td>
                  <td className="px-5 py-3.5">
                    <button onClick={() => {
                      JobsService.getResume(r.user_cpf).then(full => setSelected(full));
                    }} className="text-xs font-bold px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 flex items-center gap-1">
                      <Eye size={12} /> Ver
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {selected && (
        <CandidateModal
          app={{ ...selected, id: 0, applicant_nome: selected.user_nome, applicant_cpf: selected.user_cpf,
                 applicant_email: selected.email, applicant_phone: selected.phone,
                 cover_letter: null, status: 'novo', applied_at: selected.created_at,
                 admin_notes: null }}
          onClose={() => setSelected(null)}
          onUpdated={() => {}}
        />
      )}
    </div>
  );
}

// ── Main JobsPage ─────────────────────────────────────────────────────────────

type View = 'jobs' | 'resumes';

export default function JobsPage() {
  const [view, setView]         = useState<View>('jobs');
  const [jobs, setJobs]         = useState<Job[]>([]);
  const [total, setTotal]       = useState(0);
  const [kpi, setKpi]           = useState({ active: 0, inactive: 0, total_applications: 0, hired: 0 });
  const [loading, setLoading]   = useState(true);
  const [jobModal, setJobModal] = useState<Job | null | 'new'>(null);
  const [appsJob, setAppsJob]   = useState<Job | null>(null);
  const [search, setSearch]     = useState('');
  const [filterMode, setFilterMode] = useState('');
  const [filterStatus, setFilterStatus] = useState('');

  const loadJobs = useCallback(async () => {
    setLoading(true);
    try {
      const [jobsRes, kpiRes] = await Promise.all([
        JobsService.list({
          search: search || undefined,
          work_mode: filterMode || undefined,
          active: filterStatus === '' ? undefined : filterStatus,
          limit: 50,
        }),
        JobsService.kpi(),
      ]);
      setJobs(jobsRes.jobs || []);
      setTotal(jobsRes.total || 0);
      setKpi(kpiRes);
    } catch {
      setJobs([]);
    } finally {
      setLoading(false);
    }
  }, [search, filterMode, filterStatus]);

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

  async function toggleJob(job: Job) {
    await JobsService.toggle(job.id);
    loadJobs();
  }

  async function deleteJob(job: Job) {
    const msg = `Excluir a vaga "${job.title}"?\n\nSe houver candidaturas ela será desativada em vez de excluída.`;
    if (!confirm(msg)) return;
    const res = await JobsService.remove(job.id);
    if (res.deactivated) alert('Vaga desativada pois possui candidaturas.');
    loadJobs();
  }

  if (view === 'resumes') return <ResumesView onBack={() => setView('jobs')} />;

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
      {/* Header */}
      <header className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <h2 className="text-4xl font-black text-white tracking-tighter">Vagas & Talentos</h2>
          <p className="text-slate-400 mt-1">Gestão completa de vagas, candidatos e currículos.</p>
        </div>
        <div className="flex items-center gap-3">
          <button onClick={() => setView('resumes')}
            className="flex items-center gap-2 px-4 py-2.5 border border-slate-700 hover:border-slate-600 text-slate-400 hover:text-white rounded-xl text-sm font-bold transition-all">
            <FileText size={15} /> Currículos
          </button>
          <button onClick={() => setJobModal('new')}
            className="flex items-center gap-2 px-5 py-2.5 bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm rounded-xl transition-colors">
            <Plus size={16} /> Nova Vaga
          </button>
        </div>
      </header>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: 'Vagas Ativas',     value: kpi.active,             icon: Briefcase,  color: 'cyan' },
          { label: 'Vagas Encerradas', value: kpi.inactive,           icon: Tag,        color: 'slate' },
          { label: 'Total Candidatos', value: kpi.total_applications, icon: Users,      color: 'violet' },
          { label: 'Contratações',     value: kpi.hired,              icon: UserCheck,  color: 'emerald' },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-slate-900/40 border border-slate-800 rounded-3xl p-6 hover:border-slate-700 transition-all">
            <div className={`p-3 rounded-2xl bg-slate-800 border border-white/5 text-${color}-400 w-fit mb-4`}>
              <Icon size={22} />
            </div>
            <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">{label}</p>
            <h3 className="text-3xl font-black text-white tabular-nums tracking-tighter">{value}</h3>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Buscar por título..."
            className="w-full pl-9 pr-4 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-sm text-white focus:outline-none focus:border-cyan-500" />
        </div>
        <select value={filterMode} onChange={e => setFilterMode(e.target.value)}
          className="bg-slate-900 border border-slate-800 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-cyan-500">
          <option className="bg-slate-900 text-white" value="">Todos os modos</option>
          <option className="bg-slate-900 text-white" value="presencial">Presencial</option>
          <option className="bg-slate-900 text-white" value="hibrido">Híbrido</option>
          <option className="bg-slate-900 text-white" value="remoto">Remoto</option>
        </select>
        <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
          className="bg-slate-900 border border-slate-800 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-cyan-500">
          <option className="bg-slate-900 text-white" value="">Ativas e inativas</option>
          <option className="bg-slate-900 text-white" value="true">Somente ativas</option>
          <option className="bg-slate-900 text-white" value="false">Somente inativas</option>
        </select>
      </div>

      {/* Jobs Table */}
      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl overflow-hidden overflow-x-auto">
        {loading ? (
          <div className="flex justify-center py-16">
            <div className="w-8 h-8 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-800">
                {['Título', 'Modo', 'Tipo', 'Salário', 'Publicado', 'Expira', 'Candidatos', 'Status', ''].map(h => (
                  <th key={h} className="text-left px-4 py-4 text-[10px] font-black uppercase tracking-widest text-slate-500 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {jobs.length === 0 && (
                <tr><td colSpan={9} className="text-center py-16 text-slate-600 italic">Nenhuma vaga encontrada</td></tr>
              )}
              {jobs.map(j => (
                <tr key={j.id} className="border-b border-slate-800/50 hover:bg-slate-800/20 transition-colors">
                  <td className="px-4 py-3.5">
                    <p className="font-bold text-white">{j.title}</p>
                    {j.location && <p className="text-slate-500 text-xs flex items-center gap-1 mt-0.5"><MapPin size={10} /> {j.location}</p>}
                    {j.category && <p className="text-slate-600 text-xs">{j.category}</p>}
                  </td>
                  <td className="px-4 py-3.5">
                    <Badge label={WORK_MODE_LABELS[j.work_mode] || j.work_mode} color={WORK_MODE_COLOR[j.work_mode] || 'bg-slate-700 text-slate-300'} />
                  </td>
                  <td className="px-4 py-3.5 text-slate-400 text-xs whitespace-nowrap">{JOB_TYPE_LABELS[j.job_type] || j.job_type}</td>
                  <td className="px-4 py-3.5 text-slate-400 text-xs whitespace-nowrap">{fmtSalary(j.salary_min, j.salary_max, j.salary_hide)}</td>
                  <td className="px-4 py-3.5 text-slate-500 text-xs whitespace-nowrap">{timeAgo(j.published_at)}</td>
                  <td className="px-4 py-3.5 text-slate-500 text-xs whitespace-nowrap">{j.expires_at ? fmtDate(j.expires_at) : '—'}</td>
                  <td className="px-4 py-3.5">
                    <button onClick={() => setAppsJob(j)}
                      className="flex items-center gap-1.5 text-xs font-black text-cyan-400 hover:text-cyan-300 bg-cyan-500/10 border border-cyan-500/20 px-2.5 py-1 rounded-lg transition-all">
                      <Users size={11} /> {j.applicants_count}
                    </button>
                  </td>
                  <td className="px-4 py-3.5">
                    {j.active
                      ? <Badge label="Ativa" color="bg-emerald-500/10 text-emerald-400 border-emerald-500/20" />
                      : <Badge label="Inativa" color="bg-slate-700 text-slate-400 border-slate-600" />
                    }
                  </td>
                  <td className="px-4 py-3.5">
                    <div className="flex items-center gap-1">
                      <button onClick={() => setJobModal(j)} title="Editar"
                        className="p-1.5 rounded-lg hover:bg-slate-700 text-slate-400 hover:text-white transition-colors">
                        <Edit2 size={13} />
                      </button>
                      <button onClick={() => toggleJob(j)} title={j.active ? 'Desativar' : 'Ativar'}
                        className="p-1.5 rounded-lg hover:bg-slate-700 text-slate-400 hover:text-white transition-colors">
                        {j.active ? <ToggleRight size={15} className="text-emerald-400" /> : <ToggleLeft size={15} />}
                      </button>
                      <button onClick={() => deleteJob(j)} title="Excluir"
                        className="p-1.5 rounded-lg hover:bg-rose-500/10 text-slate-400 hover:text-rose-400 transition-colors">
                        <Trash2 size={13} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {total > 50 && (
          <div className="px-5 py-3 border-t border-slate-800 text-xs text-slate-500">
            Mostrando 50 de {total} vagas
          </div>
        )}
      </div>

      {/* Modals */}
      {jobModal !== null && (
        <JobModal
          job={jobModal === 'new' ? null : jobModal}
          onClose={() => setJobModal(null)}
          onSaved={loadJobs}
        />
      )}
      {appsJob && (
        <ApplicationsDrawer job={appsJob} onClose={() => setAppsJob(null)} />
      )}
    </div>
  );
}
