'use client'

import { useMemo, useState } from 'react'
import useSWR from 'swr'
import {
  Check,
  Star,
  RotateCcw,
  ArrowRight,
  Clock,
  TrendingUp,
  Gauge,
  Gift,
  FileText,
  Loader2,
  CheckCircle2,
} from 'lucide-react'
import { priorities, existingTools } from '@/lib/data'
import type { RecoResult } from '@/lib/recommendations'
import { RadialGauge } from '@/components/radial-gauge'
import { cn } from '@/lib/utils'

type Input = { budget: number; priorities: string[]; existingTools: string[] }

const fetcher = async (input: Input): Promise<RecoResult> => {
  const res = await fetch('/api/recommendations', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  })
  if (!res.ok) throw new Error('Erreur de calcul')
  return res.json()
}

const euros = (n: number) => n.toLocaleString('fr-FR') + ' €'

export function Configurator() {
  const [budget, setBudget] = useState(3000)
  const [selPriorities, setSelPriorities] = useState<string[]>([
    'clients',
    'ca',
    'time',
    'automate',
    'organize',
    'payments',
  ])
  const [selTools, setSelTools] = useState<string[]>(['crm'])

  const input = useMemo<Input>(
    () => ({ budget, priorities: selPriorities, existingTools: selTools }),
    [budget, selPriorities, selTools],
  )

  const { data, isLoading } = useSWR(['reco', input], () => fetcher(input), {
    keepPreviousData: true,
    revalidateOnFocus: false,
  })

  const toggle = (arr: string[], id: string, set: (v: string[]) => void) =>
    set(arr.includes(id) ? arr.filter((x) => x !== id) : [...arr, id])

  const reset = () => {
    setBudget(3000)
    setSelPriorities([])
    setSelTools([])
  }

  return (
    <section id="configurateur" className="border-b border-border/60 py-16 lg:py-24">
      <div className="mx-auto max-w-7xl px-4 lg:px-8">
        <h2 className="text-balance text-center text-3xl font-bold tracking-tight sm:text-4xl">
          Configurez votre projet en <span className="text-primary">4 étapes</span> et obtenez
          votre étude personnalisée
        </h2>
        <p className="mx-auto mt-3 max-w-2xl text-center text-muted-foreground">
          Décrivez votre projet, choisissez vos priorités, indiquez votre budget : nous vous
          proposons la meilleure solution.
        </p>

        <div className="mt-12 grid gap-5 lg:grid-cols-4">
          {/* Étape 1 — Budget */}
          <div className="rounded-2xl border border-border bg-card p-5">
            <div className="flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Votre budget estimé
              </span>
              <span className="rounded-full bg-primary/15 px-2 py-0.5 text-[11px] font-semibold text-primary">
                Étape 1
              </span>
            </div>
            <div className="mt-3 text-3xl font-extrabold text-primary">{euros(budget)}</div>
            <input
              type="range"
              min={0}
              max={100000}
              step={500}
              value={budget}
              onChange={(e) => setBudget(Number(e.target.value))}
              className="mt-4 w-full accent-[var(--primary)]"
              aria-label="Budget estimé"
            />
            <div className="mt-1 flex justify-between text-[11px] text-muted-foreground">
              <span>0 €</span>
              <span>100 000 €</span>
            </div>
            <p className="mt-3 text-xs leading-relaxed text-muted-foreground">
              Ce budget n’est pas un engagement. Il nous permet de vous proposer la meilleure
              solution adaptée à vos objectifs.
            </p>

            <div className="mt-5">
              <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Outils déjà en place
              </div>
              <div className="mt-3 space-y-2">
                {existingTools.map((t) => (
                  <Checkbox
                    key={t.id}
                    checked={selTools.includes(t.id)}
                    label={t.label}
                    onChange={() => toggle(selTools, t.id, setSelTools)}
                  />
                ))}
              </div>
            </div>
          </div>

          {/* Étape 2 — Priorités */}
          <div className="rounded-2xl border border-border bg-card p-5 lg:col-span-1">
            <div className="flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Vos priorités
              </span>
              <span className="rounded-full bg-primary/15 px-2 py-0.5 text-[11px] font-semibold text-primary">
                Étape 2
              </span>
            </div>
            <p className="mt-1 text-[11px] text-muted-foreground">(à sélectionner)</p>
            <div className="mt-3 space-y-2">
              {priorities.map((p) => (
                <Checkbox
                  key={p.id}
                  checked={selPriorities.includes(p.id)}
                  label={p.label}
                  onChange={() => toggle(selPriorities, p.id, setSelPriorities)}
                />
              ))}
            </div>
            <button
              type="button"
              onClick={reset}
              className="mt-4 inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
            >
              <RotateCcw className="size-3.5" />
              Réinitialiser
            </button>
          </div>

          {/* Étape 3 — Recommandations */}
          <div className="rounded-2xl border border-border bg-card p-5">
            <div className="flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Recommandations pour votre budget
              </span>
              <span className="rounded-full bg-primary/15 px-2 py-0.5 text-[11px] font-semibold text-primary">
                Étape 3
              </span>
            </div>

            <div className="mt-3 text-xs font-semibold text-primary">Priorités recommandées</div>
            <div className="mt-2 space-y-1.5">
              {(data?.recommended ?? []).slice(0, 6).map((m) => (
                <div key={m.id} className="flex items-center justify-between gap-2 text-sm">
                  <span className="truncate text-muted-foreground">{m.label}</span>
                  <span className="flex shrink-0 text-primary">
                    {Array.from({ length: m.stars }).map((_, i) => (
                      <Star key={i} className="size-3 fill-current" />
                    ))}
                  </span>
                </div>
              ))}
              {data && data.recommended.length === 0 && (
                <p className="text-sm text-muted-foreground">
                  Sélectionnez vos priorités pour voir nos recommandations.
                </p>
              )}
            </div>

            <div className="mt-4 space-y-2 border-t border-border pt-4 text-sm">
              <Row label="Modules recommandés" value={String(data?.recommended.length ?? 0)} />
              <Row label="Modules en réserve" value={String(data?.reserve.length ?? 0)} />
              <Row label="Budget utilisé" value={euros(data?.usedBudget ?? 0)} highlight />
              <Row label="Budget restant" value={euros(data?.remainingBudget ?? 0)} />
              <Row
                label="Temps estimé"
                value={data ? `${data.timeWeeksMin} à ${data.timeWeeksMax} semaines` : '—'}
              />
            </div>
          </div>

          {/* Étape 4 — Aperçu */}
          <div className="rounded-2xl border border-border bg-card p-5">
            <div className="flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Aperçu de votre plateforme
              </span>
              <span className="rounded-full bg-primary/15 px-2 py-0.5 text-[11px] font-semibold text-primary">
                Étape 4
              </span>
            </div>

            <div className="mt-4 flex flex-col items-center">
              <RadialGauge value={data?.automationPotential ?? 0} label="Potentiel d’automatisation" />
            </div>

            <div className="mt-4 grid grid-cols-3 gap-2 text-center">
              <MiniStat
                icon={Clock}
                value={`${data?.hoursSavedPerWeek ?? 0}h`}
                label="Temps économisé / sem."
              />
              <MiniStat icon={TrendingUp} value={`${data?.roiMonths ?? 0} mois`} label="ROI estimé" />
              <MiniStat icon={Gauge} value={data?.complexity ?? '—'} label="Complexité" />
            </div>

            <div className="mt-5 flex items-center gap-2 text-xs text-muted-foreground">
              {isLoading ? (
                <>
                  <Loader2 className="size-3.5 animate-spin" />
                  Calcul en cours…
                </>
              ) : (
                <>
                  <CheckCircle2 className="size-3.5 text-primary" />
                  Recommandation mise à jour
                </>
              )}
            </div>
          </div>
        </div>

        <p className="mt-6 flex items-center justify-center gap-2 text-center text-sm text-muted-foreground">
          <Check className="size-4 text-primary" />
          Votre plateforme sera 100 % à votre image (marque blanche) : vos couleurs, votre logo,
          votre nom de domaine.
        </p>

        <LeadForm input={input} reco={data} />
      </div>
    </section>
  )
}

function Checkbox({
  checked,
  label,
  onChange,
}: {
  checked: boolean
  label: string
  onChange: () => void
}) {
  return (
    <label className="flex cursor-pointer items-center gap-2 text-sm">
      <span
        className={cn(
          'flex size-4.5 shrink-0 items-center justify-center rounded border transition-colors',
          checked ? 'border-primary bg-primary text-primary-foreground' : 'border-border bg-background',
        )}
      >
        {checked && <Check className="size-3" />}
      </span>
      <input type="checkbox" checked={checked} onChange={onChange} className="sr-only" />
      <span className={checked ? 'text-foreground' : 'text-muted-foreground'}>{label}</span>
    </label>
  )
}

function Row({ label, value, highlight }: { label: string; value: string; highlight?: boolean }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-muted-foreground">{label}</span>
      <span className={cn('font-semibold', highlight && 'text-primary')}>{value}</span>
    </div>
  )
}

function MiniStat({
  icon: Icon,
  value,
  label,
}: {
  icon: React.ElementType
  value: string
  label: string
}) {
  return (
    <div className="flex flex-col items-center gap-1 rounded-lg bg-muted/40 p-2">
      <Icon className="size-4 text-primary" />
      <span className="text-sm font-bold leading-none">{value}</span>
      <span className="text-[10px] leading-tight text-muted-foreground">{label}</span>
    </div>
  )
}

function LeadForm({ input, reco }: { input: Input; reco?: RecoResult }) {
  const [form, setForm] = useState({
    name: '',
    email: '',
    phone: '',
    company: '',
    sector: '',
    project: '',
  })
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle')
  const [message, setMessage] = useState('')
  const [pdfUrl, setPdfUrl] = useState<string | null>(null)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setStatus('loading')
    setMessage('')
    try {
      const res = await fetch('/api/study', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, ...input }),
      })
      const json = await res.json()
      if (!res.ok) throw new Error(json.error || 'Erreur')
      setStatus('success')
      setMessage(json.message)
      setPdfUrl(json.pdfUrl ?? null)
    } catch (err) {
      setStatus('error')
      setMessage((err as Error).message)
    }
  }

  if (status === 'success') {
    return (
      <div className="mx-auto mt-10 max-w-xl rounded-2xl border border-primary/40 bg-primary/10 p-8 text-center">
        <CheckCircle2 className="mx-auto size-10 text-primary" />
        <h3 className="mt-4 text-xl font-bold">Demande envoyée !</h3>
        <p className="mt-2 text-sm text-muted-foreground">{message}</p>
        {reco && (
          <p className="mt-4 text-sm">
            Votre projet : <strong>{reco.recommended.length} modules</strong> · budget{' '}
            <strong>{euros(reco.usedBudget)}</strong> · délai{' '}
            <strong>
              {reco.timeWeeksMin} à {reco.timeWeeksMax} semaines
            </strong>
            .
          </p>
        )}
        {pdfUrl && (
          <a
            href={pdfUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-5 inline-flex items-center gap-2 rounded-full bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/20 transition-all hover:brightness-110"
          >
            <FileText className="size-4" />
            Télécharger mon étude en PDF
          </a>
        )}
      </div>
    )
  }

  return (
    <div className="mx-auto mt-10 max-w-3xl rounded-2xl border border-border bg-card p-6 lg:p-8">
      <div className="flex items-center gap-2">
        <Gift className="size-5 text-primary" />
        <h3 className="text-lg font-bold">Recevez votre étude personnalisée gratuite</h3>
      </div>
      <p className="mt-1 text-sm text-muted-foreground">
        Renseignez vos coordonnées : nous vous envoyons votre étude, une estimation budgétaire et
        une feuille de route sous 24 à 48h.
      </p>

      <form onSubmit={submit} className="mt-6 grid gap-4 sm:grid-cols-2">
        <Field
          label="Nom complet *"
          value={form.name}
          onChange={(v) => setForm({ ...form, name: v })}
          required
        />
        <Field
          label="Email *"
          type="email"
          value={form.email}
          onChange={(v) => setForm({ ...form, email: v })}
          required
        />
        <Field
          label="Téléphone"
          type="tel"
          value={form.phone}
          onChange={(v) => setForm({ ...form, phone: v })}
        />
        <Field
          label="Entreprise"
          value={form.company}
          onChange={(v) => setForm({ ...form, company: v })}
        />
        <Field
          label="Secteur d’activité"
          value={form.sector}
          onChange={(v) => setForm({ ...form, sector: v })}
          className="sm:col-span-2"
        />
        <div className="sm:col-span-2">
          <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
            Décrivez votre projet
          </label>
          <textarea
            value={form.project}
            onChange={(e) => setForm({ ...form, project: e.target.value })}
            rows={3}
            className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:border-primary"
            placeholder="Parlez-nous de votre activité et de vos objectifs…"
          />
        </div>

        {status === 'error' && (
          <p className="text-sm text-destructive sm:col-span-2">{message}</p>
        )}

        <div className="sm:col-span-2">
          <button
            type="submit"
            disabled={status === 'loading'}
            className="inline-flex w-full items-center justify-center gap-2 rounded-full bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/20 transition-all hover:brightness-110 disabled:opacity-60 sm:w-auto"
          >
            {status === 'loading' ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                Envoi…
              </>
            ) : (
              <>
                <FileText className="size-4" />
                Recevoir mon étude gratuite
                <ArrowRight className="size-4" />
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  )
}

function Field({
  label,
  value,
  onChange,
  type = 'text',
  required,
  className,
}: {
  label: string
  value: string
  onChange: (v: string) => void
  type?: string
  required?: boolean
  className?: string
}) {
  return (
    <div className={className}>
      <label className="mb-1.5 block text-xs font-medium text-muted-foreground">{label}</label>
      <input
        type={type}
        value={value}
        required={required}
        onChange={(e) => onChange(e.target.value)}
        className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:border-primary"
      />
    </div>
  )
}
