'use client'

import { useState } from 'react'

const SCHOOLS = [
  'Centrale Lyon', 'École Polytechnique', 'Mines Paris - PSL',
  'ENSAE Paris', 'IMT Atlantique', 'Université (Maths / Info)', 'HEC Paris',
]
const JOBS = [
  'Quant Researcher (Buy-side)', 'Quant Researcher (Sell-side)',
  'Structureur', 'Trader Quant', 'Risk Quant', 'Portfolio Manager Quant',
]
const LEVELS  = ['L3', 'M1', 'M2', 'En poste (reconversion)']
const SPECIAL = ["— Pas de préférence —", 'Actions / Equity', "Taux d'intérêt", 'Crédit', 'Multi-actifs', 'ML / Systematic']

interface FormState { school: string; job: string; level: string; specialty: string }
interface Result {
  masters: string
  stage1: string
  stage2: string
  skills: string
  action: string
}

// Résultat statique de démo — sera remplacé par l'appel à /api/agent/
const DEMO_RESULT: Result = {
  masters: 'El Karoui (compat. 94 %) · MASEF (88 %) · ENSAE FQ (81 %)',
  stage1:  'Quant Research intern — BNP CIB / SocGen / Natixis · 6 mois',
  stage2:  'Quant Dev intern — Amundi / BNPP AM · 6 mois',
  skills:  'Python · C++ · Calcul stochastique · sklearn · PyTorch',
  action:  'Candidater El Karoui avant mars 2026 · Préparer codility tests',
}

export function AgentForm() {
  const [form, setForm] = useState<FormState>({
    school: SCHOOLS[0], job: JOBS[0], level: 'M1', specialty: SPECIAL[0],
  })
  const [result, setResult] = useState<Result | null>(null)
  const [loading, setLoading] = useState(false)

  function set(key: keyof FormState) {
    return (e: React.ChangeEvent<HTMLSelectElement>) =>
      setForm((prev) => ({ ...prev, [key]: e.target.value }))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    try {
      // TODO: POST vers NEXT_PUBLIC_API_URL/api/agent/ avec form
      await new Promise((r) => setTimeout(r, 800)) // simulation réseau
      setResult(DEMO_RESULT)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="agent-form-demo">
      <div className="agent-form-header">
        <div className="agent-form-header-title">Générateur de parcours — Version bêta</div>
      </div>

      <form className="agent-form-body" onSubmit={handleSubmit}>
        <div className="agent-field">
          <label htmlFor="school">École / formation d&rsquo;origine</label>
          <select id="school" value={form.school} onChange={set('school')}>
            {SCHOOLS.map((s) => <option key={s}>{s}</option>)}
          </select>
        </div>
        <div className="agent-field">
          <label htmlFor="job">Métier cible en finance quant</label>
          <select id="job" value={form.job} onChange={set('job')}>
            {JOBS.map((j) => <option key={j}>{j}</option>)}
          </select>
        </div>
        <div className="agent-field">
          <label htmlFor="level">Niveau actuel</label>
          <select id="level" value={form.level} onChange={set('level')}>
            {LEVELS.map((l) => <option key={l}>{l}</option>)}
          </select>
        </div>
        <div className="agent-field">
          <label htmlFor="specialty">Spécialité souhaitée (optionnel)</label>
          <select id="specialty" value={form.specialty} onChange={set('specialty')}>
            {SPECIAL.map((s) => <option key={s}>{s}</option>)}
          </select>
        </div>
        <button type="submit" className="agent-submit" disabled={loading}>
          {loading ? 'Génération en cours…' : 'Générer mon parcours →'}
        </button>
      </form>

      {result && (
        <div className="agent-result">
          <div className="agent-result-header">
            ✓ Parcours généré — {form.school} · {form.level} · {form.job}
          </div>
          <div className="agent-result-body">
            {([
              ['Masters rec.', result.masters],
              ['Stage 1 (M1)', result.stage1],
              ['Stage 2 (M2)', result.stage2],
              ['Compétences',  result.skills],
              ['Action J+0',  result.action],
            ] as [string, string][]).map(([key, val]) => (
              <div key={key} className="result-row">
                <span className="result-key">{key}</span>
                <span className="result-val"
                  dangerouslySetInnerHTML={{ __html: val.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>') }}
                />
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="agent-footer">
        1 génération gratuite · Propulsé par Mistral AI · Fondé sur 1&nbsp;240 parcours alumni réels
      </div>
    </div>
  )
}
