"use client"

import { useMemo } from "react"
import { motion } from "framer-motion"
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, LineChart, Line, Legend
} from "recharts"
import {
  TrendingUp, TrendingDown, Users, Briefcase,
  MapPin, Clock, Star, Award, AlertTriangle, CheckCircle,
  BarChart as BarChartIcon
} from "lucide-react"
import { useOffres } from "@/app/hooks/useOffres"
import BarreLaterale from "@/app/composants/navigation/BarreLaterale"
import BarreSuperieure from "@/app/composants/en-tete/BarreSuperieure"

// Couleurs graphiques
const COULEURS = ["#1978e5", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6"]

function CarteKPI({
  titre, valeur, sous, icon, tendance, couleur, delay
}: {
  titre: string
  valeur: string | number
  sous: string
  icon: React.ReactNode
  tendance?: "hausse" | "baisse" | "neutre"
  couleur: string
  delay: number
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay }}
      whileHover={{ y: -2 }}
      className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-100 dark:border-slate-800 p-5 shadow-sm hover:shadow-md transition-all"
    >
      <div className="flex items-start justify-between mb-4">
        <div className={`p-2.5 rounded-xl ${couleur}`}>
          {icon}
        </div>
        {tendance && (
          <span className={`flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-full ${
            tendance === "hausse" ? "bg-emerald-50 text-emerald-600 dark:bg-emerald-900/20" :
            tendance === "baisse" ? "bg-red-50 text-red-500 dark:bg-red-900/20" :
            "bg-slate-100 text-slate-400 dark:bg-slate-800"
          }`}>
            {tendance === "hausse" ? <TrendingUp size={11} /> : tendance === "baisse" ? <TrendingDown size={11} /> : null}
            {tendance === "hausse" ? "En hausse" : tendance === "baisse" ? "En baisse" : "Stable"}
          </span>
        )}
      </div>
      <p className="text-3xl font-extrabold text-slate-900 dark:text-white mb-1">{valeur}</p>
      <p className="text-sm font-semibold text-slate-600 dark:text-slate-400">{titre}</p>
      <p className="text-xs text-slate-400 mt-1">{sous}</p>
    </motion.div>
  )
}

export default function PageAnalyses() {
  const { offres } = useOffres()

  // ── Calculs analytiques ──────────────────────────────────────────
  const stats = useMemo(() => {
    const total        = offres.length
    const actives      = offres.filter(o => o.statut === "Actif").length
    const brouillons   = offres.filter(o => o.statut === "Brouillon").length
    const urgentes     = offres.filter(o => o.statut === "Urgent").length
    const cloturees    = offres.filter(o => o.statut === "Clôturé").length
    const totalCandidats = offres.reduce((a, o) => a + o.candidats, 0)
    const tauxActives  = total > 0 ? Math.round((actives / total) * 100) : 0

    // Répartition par contrat
    const parContrat = ["CDI", "CDD", "Interim", "Freelance"].map(c => ({
      name: c,
      value: offres.filter(o => o.contrat === c).length,
    })).filter(d => d.value > 0)

    // Répartition par statut
    const parStatut = [
      { name: "Actif",     value: actives,    color: "#10b981" },
      { name: "Brouillon", value: brouillons, color: "#f59e0b" },
      { name: "Urgent",    value: urgentes,   color: "#f97316" },
      { name: "Clôturé",   value: cloturees,  color: "#94a3b8" },
    ].filter(d => d.value > 0)

    // Offres par localisation
    const locMap: Record<string, number> = {}
    offres.forEach(o => {
      const loc = o.localisation || "Non défini"
      locMap[loc] = (locMap[loc] || 0) + 1
    })
    const parLieu = Object.entries(locMap)
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 6)

    // Candidats par offre (top 5)
    const topOffres = [...offres]
      .sort((a, b) => b.candidats - a.candidats)
      .slice(0, 5)
      .map(o => ({ name: o.poste.length > 20 ? o.poste.slice(0, 20) + "…" : o.poste, candidats: o.candidats }))

    // Évolution des publications (par jour sur 7 derniers jours)
    const evolution = Array.from({ length: 7 }, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() - (6 - i))
      const label = date.toLocaleDateString("fr-FR", { weekday: "short", day: "numeric" })
      const count = offres.filter(o => {
        const d = new Date(o.dateCreation)
        return d.toDateString() === date.toDateString()
      }).length
      return { label, offres: count }
    })

    return { total, actives, brouillons, urgentes, cloturees, totalCandidats, tauxActives, parContrat, parStatut, parLieu, topOffres, evolution }
  }, [offres])

  // ── Rendu vide ───────────────────────────────────────────────────
  if (offres.length === 0) {
    return (
      <div className="flex h-screen overflow-hidden bg-background-light dark:bg-background-dark">
        <BarreLaterale />
        <main className="flex-1 flex flex-col overflow-hidden">
          <BarreSuperieure />
          <div className="flex-1 flex items-center justify-center">
            <div className="text-center">
              <div className="w-20 h-20 bg-slate-100 dark:bg-slate-800 rounded-2xl flex items-center justify-center mx-auto mb-4">
                <BarChartIcon className="text-slate-400" size={32} />
              </div>
              <h2 className="text-xl font-bold text-slate-900 dark:text-white mb-2">Aucune donnée à analyser</h2>
              <p className="text-slate-500 text-sm">Publiez des offres pour voir vos analyses apparaître ici.</p>
            </div>
          </div>
        </main>
      </div>
    )
  }

  return (
    <div className="flex h-screen overflow-hidden bg-background-light dark:bg-background-dark text-slate-900 dark:text-slate-100">
      <BarreLaterale />

      <main className="flex-1 flex flex-col overflow-hidden">
        <BarreSuperieure />

        <div className="flex-1 overflow-y-auto p-8 space-y-8">

          {/* Titre */}
          <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}>
            <h1 className="text-3xl font-extrabold text-slate-900 dark:text-white tracking-tight">
              Analyses & Performances
            </h1>
            <p className="text-slate-500 mt-1 text-sm">
              Vue d&apos;ensemble de votre activité de recrutement — {offres.length} offre{offres.length > 1 ? "s" : ""} analysée{offres.length > 1 ? "s" : ""}
            </p>
          </motion.div>

          {/* KPIs */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <CarteKPI
              titre="Offres publiées"
              valeur={stats.total}
              sous="Total toutes catégories"
              icon={<Briefcase size={18} className="text-blue-600" />}
              couleur="bg-blue-50 dark:bg-blue-900/20"
              tendance="hausse"
              delay={0}
            />
            <CarteKPI
              titre="Offres actives"
              valeur={stats.actives}
              sous={`${stats.tauxActives}% du total`}
              icon={<CheckCircle size={18} className="text-emerald-600" />}
              couleur="bg-emerald-50 dark:bg-emerald-900/20"
              tendance={stats.tauxActives > 50 ? "hausse" : "baisse"}
              delay={0.1}
            />
            <CarteKPI
              titre="Total candidats"
              valeur={stats.totalCandidats.toLocaleString("fr-FR")}
              sous="Sur toutes vos offres"
              icon={<Users size={18} className="text-purple-600" />}
              couleur="bg-purple-50 dark:bg-purple-900/20"
              tendance={stats.totalCandidats > 0 ? "hausse" : "neutre"}
              delay={0.2}
            />
            <CarteKPI
              titre="Offres urgentes"
              valeur={stats.urgentes}
              sous="Nécessitent une action"
              icon={<AlertTriangle size={18} className="text-orange-600" />}
              couleur="bg-orange-50 dark:bg-orange-900/20"
              tendance={stats.urgentes > 0 ? "baisse" : "neutre"}
              delay={0.3}
            />
          </div>

          {/* Graphiques ligne 1 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

            {/* Évolution publications */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.3 }}
              className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-100 dark:border-slate-800 p-6 shadow-sm"
            >
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h2 className="font-bold text-slate-900 dark:text-white">Publications cette semaine</h2>
                  <p className="text-xs text-slate-400 mt-0.5">Offres publiées par jour</p>
                </div>
                <TrendingUp size={18} className="text-blue-500" />
              </div>
              <ResponsiveContainer width="100%" height={200}>
                <LineChart data={stats.evolution}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                  <XAxis dataKey="label" tick={{ fontSize: 11, fill: "#94a3b8" }} />
                  <YAxis tick={{ fontSize: 11, fill: "#94a3b8" }} allowDecimals={false} />
                  <Tooltip
                    contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0", fontSize: 12 }}
                    labelStyle={{ fontWeight: "bold" }}
                  />
                  <Line
                    type="monotone"
                    dataKey="offres"
                    stroke="#1978e5"
                    strokeWidth={2.5}
                    dot={{ fill: "#1978e5", r: 4 }}
                    activeDot={{ r: 6 }}
                    name="Offres publiées"
                  />
                </LineChart>
              </ResponsiveContainer>
            </motion.div>

            {/* Répartition statuts */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.35 }}
              className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-100 dark:border-slate-800 p-6 shadow-sm"
            >
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h2 className="font-bold text-slate-900 dark:text-white">Répartition par statut</h2>
                  <p className="text-xs text-slate-400 mt-0.5">Distribution de vos offres</p>
                </div>
                <Award size={18} className="text-amber-500" />
              </div>
              {stats.parStatut.length > 0 ? (
                <div className="flex items-center gap-6">
                  <ResponsiveContainer width="50%" height={180}>
                    <PieChart>
                      <Pie
                        data={stats.parStatut}
                        cx="50%"
                        cy="50%"
                        innerRadius={50}
                        outerRadius={80}
                        paddingAngle={3}
                        dataKey="value"
                      >
                        {stats.parStatut.map((entry, i) => (
                          <Cell key={i} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0", fontSize: 12 }} />
                    </PieChart>
                  </ResponsiveContainer>
                  <div className="flex-1 space-y-2">
                    {stats.parStatut.map((s, i) => (
                      <div key={i} className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: s.color }} />
                          <span className="text-xs text-slate-600 dark:text-slate-400">{s.name}</span>
                        </div>
                        <span className="text-xs font-bold text-slate-900 dark:text-white">{s.value}</span>
                      </div>
                    ))}
                  </div>
                </div>
              ) : (
                <p className="text-sm text-slate-400 text-center py-8">Aucune donnée</p>
              )}
            </motion.div>
          </div>

          {/* Graphiques ligne 2 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

            {/* Top offres par candidats */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
              className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-100 dark:border-slate-800 p-6 shadow-sm"
            >
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h2 className="font-bold text-slate-900 dark:text-white">Top offres par candidats</h2>
                  <p className="text-xs text-slate-400 mt-0.5">Les 5 offres les plus attractives</p>
                </div>
                <Star size={18} className="text-amber-500" />
              </div>
              {stats.topOffres.length > 0 ? (
                <ResponsiveContainer width="100%" height={200}>
                  <BarChart data={stats.topOffres} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" horizontal={false} />
                    <XAxis type="number" tick={{ fontSize: 11, fill: "#94a3b8" }} allowDecimals={false} />
                    <YAxis dataKey="name" type="category" tick={{ fontSize: 11, fill: "#94a3b8" }} width={100} />
                    <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0", fontSize: 12 }} />
                    <Bar dataKey="candidats" fill="#1978e5" radius={[0, 6, 6, 0]} name="Candidats" />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-sm text-slate-400 text-center py-8">Aucune offre avec candidats</p>
              )}
            </motion.div>

            {/* Répartition par lieu */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.45 }}
              className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-100 dark:border-slate-800 p-6 shadow-sm"
            >
              <div className="flex items-center justify-between mb-6">
                <div>
                  <h2 className="font-bold text-slate-900 dark:text-white">Offres par localisation</h2>
                  <p className="text-xs text-slate-400 mt-0.5">Répartition géographique</p>
                </div>
                <MapPin size={18} className="text-emerald-500" />
              </div>
              {stats.parLieu.length > 0 ? (
                <div className="space-y-3">
                  {stats.parLieu.map((l, i) => {
                    const max = stats.parLieu[0].value
                    const pct = Math.round((l.value / max) * 100)
                    return (
                      <div key={i} className="flex items-center gap-3">
                        <span className="text-xs text-slate-500 w-24 truncate">{l.name}</span>
                        <div className="flex-1 h-2 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                          <motion.div
                            initial={{ width: 0 }}
                            animate={{ width: `${pct}%` }}
                            transition={{ delay: 0.5 + i * 0.05, duration: 0.6, ease: "easeOut" }}
                            className="h-full rounded-full"
                            style={{ backgroundColor: COULEURS[i % COULEURS.length] }}
                          />
                        </div>
                        <span className="text-xs font-bold text-slate-900 dark:text-white w-4 text-right">{l.value}</span>
                      </div>
                    )
                  })}
                </div>
              ) : (
                <p className="text-sm text-slate-400 text-center py-8">Aucune donnée</p>
              )}
            </motion.div>
          </div>

          {/* Répartition contrats */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-100 dark:border-slate-800 p-6 shadow-sm"
          >
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="font-bold text-slate-900 dark:text-white">Répartition par type de contrat</h2>
                <p className="text-xs text-slate-400 mt-0.5">CDI, CDD, Interim, Freelance</p>
              </div>
              <Clock size={18} className="text-purple-500" />
            </div>
            {stats.parContrat.length > 0 ? (
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={stats.parContrat}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                  <XAxis dataKey="name" tick={{ fontSize: 12, fill: "#94a3b8" }} />
                  <YAxis tick={{ fontSize: 11, fill: "#94a3b8" }} allowDecimals={false} />
                  <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0", fontSize: 12 }} />
                  <Bar dataKey="value" radius={[6, 6, 0, 0]} name="Offres">
                    {stats.parContrat.map((_, i) => (
                      <Cell key={i} fill={COULEURS[i % COULEURS.length]} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <p className="text-sm text-slate-400 text-center py-8">Aucune donnée</p>
            )}
          </motion.div>

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