import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import {
  MapPin, Clock, Users, CheckCircle, ChevronLeft, Briefcase,
  Building2, X, AlertCircle,
} 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} dias 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!)}`
}

function maskCpf(v: string) {
  return v.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2')
}
function maskPhone(v: string) {
  return v.replace(/\D/g, '').replace(/^(\d{2})(\d)/, '($1) $2').replace(/(\d{5})(\d)/, '$1-$2')
}

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 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 APP_STATUS_LABELS: Record<string, string> = {
  novo: 'Candidatura enviada', em_analise: 'Em análise',
  aprovado: 'Aprovado!', reprovado: 'Não selecionado', contratado: 'Contratado!',
}
const APP_STATUS_COLORS: Record<string, string> = {
  novo: 'text-slate-400', em_analise: 'text-blue-400',
  aprovado: 'text-emerald-400', reprovado: 'text-rose-400', contratado: 'text-violet-400',
}

// ── Apply Modal ───────────────────────────────────────────────────────────────

function ApplyModal({
  job, user, onClose, onSuccess,
}: {
  job: any; user: any; onClose: () => void; onSuccess: () => void
}) {
  const tenant = useTenantCtx()
  const [form, setForm] = useState({
    applicant_nome:  user?.nome  || '',
    applicant_cpf:   user?.cpf   || '',
    applicant_phone: user?.telefone || '',
    applicant_email: user?.email || '',
    cover_letter:    '',
  })
  const [err, setErr]     = useState('')
  const [loading, setLoading] = useState(false)
  const [done, setDone]   = useState(false)

  function f(k: string, v: string) { setForm(p => ({ ...p, [k]: v })) }

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true); setErr('')
    try {
      await JobsAPI.apply(job.id, form)
      setDone(true)
      setTimeout(onSuccess, 2500)
    } catch (ex: any) {
      setErr(ex.response?.data?.error || 'Erro ao enviar candidatura')
    } finally { setLoading(false) }
  }

  if (done) {
    return (
      <div className="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4">
        <div className="bg-slate-900 border border-slate-800 rounded-3xl p-10 text-center max-w-sm w-full space-y-4">
          <CheckCircle size={56} className="text-emerald-400 mx-auto" />
          <h3 className="text-xl font-black text-white">Candidatura enviada!</h3>
          <p className="text-slate-400 text-sm">Boa sorte! Acompanhe o status na sua área do cliente.</p>
        </div>
      </div>
    )
  }

  return (
    <div className="fixed inset-0 bg-black/70 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-md max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-5 border-b border-slate-800 sticky top-0 bg-slate-900">
          <div>
            <h3 className="font-black text-white">Candidatar-se</h3>
            <p className="text-slate-500 text-xs">{job.title}</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white"><X size={20} /></button>
        </div>

        <form onSubmit={submit} className="p-5 space-y-4">
          {[
            { label: 'Nome completo *', key: 'applicant_nome', type: 'text', mask: null },
            { label: 'CPF *', key: 'applicant_cpf', type: 'text', mask: maskCpf },
            { label: 'Telefone / WhatsApp', key: 'applicant_phone', type: 'tel', mask: maskPhone },
            { label: 'E-mail', key: 'applicant_email', type: 'email', mask: null },
          ].map(({ label, key, type, mask }) => (
            <div key={key}>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">{label}</label>
              <input type={type} required={key === 'applicant_nome' || key === 'applicant_cpf'}
                value={(form as any)[key]}
                onChange={e => { const v = mask ? mask(e.target.value) : e.target.value; f(key, v) }}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-amber-500"
              />
            </div>
          ))}

          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Carta de Apresentação</label>
            <textarea rows={4} value={form.cover_letter}
              onChange={e => f('cover_letter', e.target.value)}
              placeholder="Conte um pouco sobre você e por que se interessa por esta vaga..."
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-amber-500 resize-none"
            />
          </div>

          {err && (
            <div className="flex items-center gap-2 text-rose-400 text-sm bg-rose-500/10 border border-rose-500/20 rounded-xl px-4 py-3">
              <AlertCircle size={14} /> {err}
            </div>
          )}

          <button type="submit" disabled={loading}
            className="w-full py-4 rounded-2xl font-black text-black transition-all hover:opacity-90 disabled:opacity-40"
            style={{ background: tenant.primary_color }}>
            {loading ? 'Enviando…' : 'Enviar Candidatura'}
          </button>
        </form>
      </div>
    </div>
  )
}

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

export default function VagaDetailPage({ user }: { user?: any }) {
  const { id }     = useParams<{ id: string }>()
  const tenant     = useTenantCtx()

  const [job, setJob]         = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [applying, setApplying] = useState(false)
  const [myApp, setMyApp]     = useState<any>(null)

  useEffect(() => {
    if (!id) return
    JobsAPI.get(+id)
      .then(setJob)
      .catch(() => setJob(null))
      .finally(() => setLoading(false))

    // Verifica se já se candidatou
    if (user) {
      JobsAPI.myApplications()
        .then(apps => {
          const match = apps.find((a: any) => String(a.job_id) === String(id))
          if (match) setMyApp(match)
        })
        .catch(() => {})
    }
  }, [id, user])

  if (loading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center pt-16">
        <div className="w-8 h-8 border-2 border-t-transparent rounded-full animate-spin" style={{ borderColor: tenant.primary_color }} />
      </div>
    )
  }

  if (!job) {
    return (
      <div className="min-h-screen bg-black flex flex-col items-center justify-center pt-16 gap-4">
        <p className="text-slate-600 italic">Vaga não encontrada ou encerrada.</p>
        <Link to="/vagas" className="text-sm font-bold text-amber-400 hover:text-amber-300">← Ver todas as vagas</Link>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-black pt-16">
      {/* Back */}
      <div className="max-w-4xl mx-auto px-4 pt-6">
        <Link to="/vagas" className="inline-flex items-center gap-2 text-sm text-slate-500 hover:text-white transition-colors mb-6">
          <ChevronLeft size={16} /> Todas as vagas
        </Link>
      </div>

      <div className="max-w-4xl mx-auto px-4 pb-20">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Main content */}
          <div className="lg:col-span-2 space-y-8">
            {/* Header */}
            <div>
              <div className="flex flex-wrap items-start justify-between gap-3 mb-4">
                <div>
                  <h1 className="text-3xl font-black text-white tracking-tighter">{job.title}</h1>
                  {job.category && (
                    <p className="text-slate-500 text-sm mt-1">{job.category}</p>
                  )}
                </div>
                <span className={`text-xs font-black px-3 py-1 rounded-xl border ${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-x-5 gap-y-2 text-sm text-slate-400">
                {job.location && <span className="flex items-center gap-1.5"><MapPin size={13} /> {job.location}</span>}
                <span className="flex items-center gap-1.5"><Building2 size={13} /> {JOB_TYPE_LABELS[job.job_type] || job.job_type}</span>
                <span className="flex items-center gap-1.5"><Clock size={13} /> {timeAgo(job.published_at)}</span>
                <span className="flex items-center gap-1.5"><Users size={13} /> {job.applicants_count} candidato{job.applicants_count !== 1 ? 's' : ''}</span>
              </div>
            </div>

            {/* Description */}
            <div>
              <h2 className="text-lg font-black text-white mb-3">Descrição da Vaga</h2>
              <div className="text-slate-300 text-sm leading-relaxed whitespace-pre-line">{job.description}</div>
            </div>

            {/* Requirements */}
            {job.requirements && (
              <div>
                <h2 className="text-lg font-black text-white mb-3">Requisitos</h2>
                <div className="text-slate-300 text-sm leading-relaxed whitespace-pre-line">{job.requirements}</div>
              </div>
            )}

            {/* Benefits */}
            {job.benefits && (
              <div>
                <h2 className="text-lg font-black text-white mb-3">Benefícios</h2>
                <div className="text-slate-300 text-sm leading-relaxed whitespace-pre-line">{job.benefits}</div>
              </div>
            )}
          </div>

          {/* Sidebar */}
          <div className="space-y-4">
            {/* Job info card */}
            <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-4 sticky top-24">
              <div>
                <p className="text-xs text-slate-500 mb-1">Salário</p>
                <p className="text-xl font-black" style={{ color: tenant.primary_color }}>
                  {fmtSalary(job.salary_min, job.salary_max, job.salary_hide)}
                </p>
              </div>
              {job.slots > 1 && (
                <div>
                  <p className="text-xs text-slate-500">Vagas disponíveis</p>
                  <p className="text-white font-bold">{job.slots}</p>
                </div>
              )}
              {job.expires_at && (
                <div>
                  <p className="text-xs text-slate-500">Encerra em</p>
                  <p className="text-white font-bold">{new Date(job.expires_at).toLocaleDateString('pt-BR')}</p>
                </div>
              )}

              {/* Apply button / status */}
              {myApp ? (
                <div className="bg-slate-800/50 border border-slate-700 rounded-xl p-4 text-center">
                  <CheckCircle size={20} className={`mx-auto mb-2 ${APP_STATUS_COLORS[myApp.status] || 'text-emerald-400'}`} />
                  <p className="font-bold text-white text-sm">{APP_STATUS_LABELS[myApp.status] || 'Candidatura enviada'}</p>
                  <p className="text-slate-500 text-xs mt-1">
                    em {new Date(myApp.applied_at).toLocaleDateString('pt-BR')}
                  </p>
                </div>
              ) : (
                <button
                  onClick={() => setApplying(true)}
                  className="w-full py-4 rounded-2xl font-black text-black text-sm transition-all hover:opacity-90 active:scale-95"
                  style={{ background: tenant.primary_color }}>
                  Candidatar-se
                </button>
              )}

              {!user && !myApp && (
                <p className="text-center text-xs text-slate-500">
                  <Link to="/login" className="underline hover:text-white">Faça login</Link> para preencher automaticamente
                </p>
              )}
            </div>

            {/* Back link */}
            <Link to="/vagas"
              className="flex items-center justify-center gap-2 w-full py-3 border border-slate-800 hover:border-slate-700 rounded-2xl text-sm text-slate-400 hover:text-white transition-all">
              <Briefcase size={14} /> Ver todas as vagas
            </Link>
          </div>
        </div>
      </div>

      {applying && (
        <ApplyModal
          job={job}
          user={user}
          onClose={() => setApplying(false)}
          onSuccess={() => {
            setApplying(false)
            // Refresh applications
            if (user) {
              JobsAPI.myApplications()
                .then(apps => {
                  const match = apps.find((a: any) => String((a as any).job_id) === String(id))
                  if (match) setMyApp(match)
                })
                .catch(() => {})
            }
          }}
        />
      )}
    </div>
  )
}
