"use client"

import { Suspense, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { motion } from "framer-motion"
import { useOffres } from "@/app/hooks/useOffres"
import BarreProgression from "@/app/composants/offres/creation/BarreProgression"

function ContenuEtape5() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { ajouterOffre } = useOffres()

  const [publication, setPublication] = useState<"idle" | "loading" | "succes">("idle")

  const metier           = searchParams.get("metier")           || "Non renseigné"
  const ville            = searchParams.get("ville")            || "Non renseigné"
  const contrat          = searchParams.get("contrat")          || "Non renseigné"
  const typeRemuneration = searchParams.get("typeRemuneration") || ""
  const montantMin       = searchParams.get("montantMin")       || ""
  const montantMax       = searchParams.get("montantMax")       || ""
  const frequence        = searchParams.get("frequence")        || ""
  const avantages        = searchParams.get("avantages")
    ? searchParams.get("avantages")!.split(",").filter(Boolean)
    : []

  const salaire = montantMin && montantMax
    ? `${Number(montantMin).toLocaleString()} - ${Number(montantMax).toLocaleString()} FCFA`
    : montantMin
    ? `${Number(montantMin).toLocaleString()} FCFA`
    : "À négocier"

  const allerRetour = () => {
    router.push(`/entreprise/offres/creation/etape-4?metier=${encodeURIComponent(metier)}`)
  }

  const handlePublier = (statut: "Actif" | "Brouillon") => {
    setPublication("loading")
    try {
      ajouterOffre({
        poste: metier,
        localisation: ville,
        contrat,
        salaire,
        typeRemuneration,
        frequence,
        avantages,
        statut,
      })
      setPublication("succes")
      setTimeout(() => {
        // ✅ Redirection vers le tableau de bord
        router.push("/entreprise/tableau-de-bord")
      }, 2500)
    } catch (e) {
      console.error("Erreur publication:", e)
      setPublication("idle")
    }
  }

  // Écran de succès
  if (publication === "succes") {
    return (
      <div className="fixed inset-0 bg-white dark:bg-background-dark flex flex-col items-center justify-center gap-6 z-50">
        <motion.div
          initial={{ scale: 0, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ type: "spring", stiffness: 200, damping: 15 }}
          className="relative"
        >
          <motion.div
            initial={{ scale: 1, opacity: 0.6 }}
            animate={{ scale: 1.8, opacity: 0 }}
            transition={{ duration: 1.2, repeat: Infinity }}
            className="absolute inset-0 rounded-full bg-emerald-400"
          />
          <div className="relative w-28 h-28 rounded-full bg-emerald-500 flex items-center justify-center shadow-xl shadow-emerald-200">
            <motion.span
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.2, duration: 0.5 }}
              className="material-symbols-outlined text-white text-6xl"
            >
              check
            </motion.span>
          </div>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="text-center"
        >
          <h2 className="text-3xl font-extrabold text-slate-900 dark:text-white mb-2">
            Offre publiée avec succès !
          </h2>
          <p className="text-slate-500">
            Votre offre pour{" "}
            <span className="font-semibold text-primary">{metier}</span>{" "}
            est maintenant visible.
          </p>
        </motion.div>

        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.8 }}
          className="flex flex-col items-center gap-2 mt-2"
        >
          <div className="w-48 h-1.5 bg-slate-100 rounded-full overflow-hidden">
            <motion.div
              initial={{ width: "0%" }}
              animate={{ width: "100%" }}
              transition={{ delay: 0.8, duration: 1.7, ease: "linear" }}
              className="h-full bg-emerald-500 rounded-full"
            />
          </div>
          <p className="text-xs text-slate-400">Redirection vers vos offres...</p>
        </motion.div>
      </div>
    )
  }

  return (
    <main className="flex flex-col bg-background-light dark:bg-background-dark min-h-screen">

      <header className="h-16 flex items-center justify-between px-8 bg-white/90 dark:bg-slate-900/90 backdrop-blur-md border-b border-slate-200/60 dark:border-slate-700/50 shadow-sm">
        <div className="flex items-center gap-4">
          <button onClick={allerRetour} className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-slate-800 transition">
            <span className="material-symbols-outlined text-slate-500">arrow_back</span>
          </button>
          <h2 className="text-lg font-bold">Créer une offre d&apos;emploi</h2>
          {metier !== "Non renseigné" && (
            <span className="px-3 py-1 bg-primary/10 text-primary rounded-full text-sm font-semibold">
              {metier}
            </span>
          )}
        </div>
        <div className="flex items-center gap-4">
          <button className="relative p-2 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full transition-colors">
            <span className="material-symbols-outlined">notifications</span>
            <span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full border-2 border-white dark:border-slate-900" />
          </button>
          <button className="flex items-center gap-2 px-3 py-1.5 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg transition-colors text-sm font-semibold">
            Aide <span className="material-symbols-outlined text-sm">help</span>
          </button>
        </div>
      </header>

      <div className="mx-auto w-full max-w-5xl px-8 py-10">

        <BarreProgression etape={5} />

        <div className="mb-10">
          <h1 className="text-4xl font-extrabold tracking-tight text-slate-900 dark:text-white">
            Récapitulatif et Validation
          </h1>
          <p className="mt-2 text-lg text-slate-500">
            Vérifiez les détails de votre offre avant de la rendre visible aux candidats.
          </p>
        </div>

        <div className="grid gap-6">

          {/* Poste */}
          <div className="relative overflow-hidden rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-6 shadow-sm hover:shadow-md transition-shadow">
            <div className="flex items-start justify-between">
              <div className="flex gap-4">
                <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10 text-primary shrink-0">
                  <span className="material-symbols-outlined">title</span>
                </div>
                <div>
                  <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-400">Poste &amp; Catégorie</h3>
                  <p className="mt-1 text-xl font-bold text-slate-900 dark:text-white">{metier}</p>
                  <p className="text-slate-500">Offre d&apos;emploi</p>
                </div>
              </div>
              <button onClick={() => router.push("/entreprise/offres/creation/etape-1")}
                className="flex items-center gap-1 text-sm font-semibold text-primary hover:underline shrink-0">
                <span className="material-symbols-outlined text-lg">edit</span> Modifier
              </button>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">

            {/* Lieu & Contrat */}
            <div className="relative overflow-hidden rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-6 shadow-sm">
              <div className="flex items-start justify-between mb-4">
                <div className="flex gap-4">
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400 shrink-0">
                    <span className="material-symbols-outlined">location_on</span>
                  </div>
                  <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-400 pt-1">Lieu &amp; Contrat</h3>
                </div>
                <button onClick={() => router.push(`/entreprise/offres/creation/etape-3?metier=${encodeURIComponent(metier)}`)}
                  className="flex items-center gap-1 text-sm font-semibold text-primary hover:underline shrink-0">
                  <span className="material-symbols-outlined text-lg">edit</span> Modifier
                </button>
              </div>
              <div className="pl-16 flex flex-col gap-2">
                <div className="flex items-center gap-2">
                  <span className="material-symbols-outlined text-slate-400 text-lg">article</span>
                  <span className="font-bold">{contrat}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="material-symbols-outlined text-slate-400 text-lg">map</span>
                  <span className="text-slate-600 dark:text-slate-400">{ville}</span>
                </div>
              </div>
            </div>

            {/* Budget & Avantages */}
            <div className="relative overflow-hidden rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-6 shadow-sm">
              <div className="flex items-start justify-between mb-4">
                <div className="flex gap-4">
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-purple-100 text-purple-600 dark:bg-purple-900/30 dark:text-purple-400 shrink-0">
                    <span className="material-symbols-outlined">payments</span>
                  </div>
                  <h3 className="text-sm font-semibold uppercase tracking-wider text-slate-400 pt-1">Budget &amp; Avantages</h3>
                </div>
                <button onClick={() => router.push(`/entreprise/offres/creation/etape-4?metier=${encodeURIComponent(metier)}`)}
                  className="flex items-center gap-1 text-sm font-semibold text-primary hover:underline shrink-0">
                  <span className="material-symbols-outlined text-lg">edit</span> Modifier
                </button>
              </div>
              <div className="pl-16">
                <p className="text-2xl font-bold text-slate-900 dark:text-white">{salaire}</p>
                <p className="text-xs text-slate-500 mb-4">{frequence} • {typeRemuneration}</p>
                {avantages.length > 0 && (
                  <ul className="space-y-2">
                    {avantages.map((a) => (
                      <li key={a} className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400">
                        <span className="material-symbols-outlined text-green-500 text-lg">check_circle</span>
                        {a}
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            </div>

          </div>

          {/* Bannière */}
          <div className="flex items-center gap-3 rounded-lg border border-primary/20 bg-primary/5 p-4 text-primary">
            <span className="material-symbols-outlined">sync</span>
            <p className="text-sm font-medium">
              Votre offre sera sauvegardée localement et visible immédiatement dans la liste des offres.
            </p>
          </div>

          {/* Footer actions */}
          <div className="mt-4 flex flex-col sm:flex-row items-center justify-end gap-4 border-t border-slate-200 dark:border-slate-800 pt-8 pb-8">
            <button
              onClick={() => handlePublier("Brouillon")}
              disabled={publication === "loading"}
              className="w-full sm:w-auto px-8 py-3 text-sm font-bold text-slate-600 dark:text-slate-300 bg-transparent border border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-lg transition-colors disabled:opacity-50"
            >
              Enregistrer en brouillon
            </button>
            <motion.button
              whileHover={{ scale: 1.03 }}
              whileTap={{ scale: 0.97 }}
              onClick={() => handlePublier("Actif")}
              disabled={publication === "loading"}
              className="w-full sm:w-auto px-10 py-3 text-sm font-bold text-white bg-primary hover:bg-primary/90 rounded-lg shadow-lg shadow-primary/20 transition-all flex items-center justify-center gap-2 disabled:opacity-70"
            >
              {publication === "loading" ? (
                <>
                  <motion.span
                    animate={{ rotate: 360 }}
                    transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                    className="material-symbols-outlined text-lg"
                  >
                    progress_activity
                  </motion.span>
                  Publication...
                </>
              ) : (
                <>
                  Publier l&apos;offre
                  <span className="material-symbols-outlined text-lg">rocket_launch</span>
                </>
              )}
            </motion.button>
          </div>

        </div>
      </div>
    </main>
  )
}

export default function PageEtape5() {
  return (
    <Suspense fallback={
      <div className="flex items-center justify-center min-h-screen text-slate-500">Chargement...</div>
    }>
      <ContenuEtape5 />
    </Suspense>
  )
}