"use client";
import { useState, useEffect } from "react";
import { Plus, Trash2, Megaphone, CheckCircle, XCircle, Power, Save, Sparkles, Send, MessageCircle, ExternalLink, Image as ImageIcon } from "lucide-react";
import { toast } from "@/components/ui/Toaster";
import { formatNumber } from "@/lib/utils";
import { HeroCardsEditor } from "@/components/admin/HeroCardsEditor";
import { InFeedAdsEditor } from "@/components/admin/InFeedAdsEditor";

export default function AdminAdsPage() {
  const [ads, setAds] = useState<any[]>([]);
  const [adsEnabled, setAdsEnabled] = useState<boolean>(true);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ title: "", placement: "banner", imageUrl: "", linkUrl: "", isActive: true });

  const fetchAds = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/ads");
      const data = await res.json();

      if (Array.isArray(data)) {
        setAds(data);
      } else if (data?.ads) {
        setAds(data.ads);
        if (data.adsEnabled !== undefined) setAdsEnabled(data.adsEnabled);
      }
    } catch (e) {
      toast("Erreur de chargement", "error");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchAds(); }, []);

  const toggleGlobalAds = async () => {
    const newState = !adsEnabled;
    setAdsEnabled(newState);
    const res = await fetch("/api/admin/ads", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ adsEnabled: newState }),
    });
    if (res.ok) {
      toast(newState ? "Publicités activées sur le site" : "Toutes les publicités ont été désactivées", "success");
    } else {
      toast("Erreur de modification", "error");
      setAdsEnabled(!newState);
    }
  };

  const toggleAdActive = async (id: string, currentActive: boolean) => {
    const res = await fetch("/api/admin/ads", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, isActive: !currentActive }),
    });
    if (res.ok) {
      toast("Statut de la publicité mis à jour", "success");
      fetchAds();
    } else {
      toast("Erreur lors de la mise à jour", "error");
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.title) { toast("Titre requis", "error"); return; }
    const res = await fetch("/api/admin/ads", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    if (res.ok) {
      toast("Publicité créée avec succès", "success");
      setShowForm(false);
      setForm({ title: "", placement: "banner", imageUrl: "", linkUrl: "", isActive: true });
      fetchAds();
    } else {
      toast("Erreur lors de la création", "error");
    }
  };

  const deleteAd = async (id: string) => {
    if (!confirm("Voulez-vous vraiment supprimer cette publicité ?")) return;
    const res = await fetch(`/api/admin/ads?id=${id}`, { method: "DELETE" });
    if (res.ok) {
      toast("Publicité supprimée", "success");
      fetchAds();
    } else {
      toast("Erreur lors de la suppression", "error");
    }
  };

  return (
    <div className="p-6 md:p-8 animate-fade-in space-y-10">
      
      {/* 📌 SECTION 1 : GESTION DES 3 PANCARTES / BANNIÈRES HERO DE L'ACCUEIL */}
      <HeroCardsEditor themeColor="#e05a68" />

      {/* 📌 SECTION 2 : GESTION DES PUBS PERSONNALISÉES DANS LA GRILLE VIDÉO */}
      <InFeedAdsEditor themeColor="#e05a68" siteName="mtbr" />

      {/* SECTION 3 : GESTION DES AUTRES PUBLICITÉS DU SITE */}
      <div>
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
          <div>
            <h2 className="text-2xl font-black text-white mb-1">Autres Publicités & Bannières</h2>
            <p style={{ color: "var(--text-secondary)" }}>{ads.length} annonce(s) classique(s) enregistrée(s)</p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={toggleGlobalAds}
              style={{
                backgroundColor: adsEnabled ? "#059669" : "#dc2626",
                color: "#ffffff",
                border: adsEnabled ? "1px solid #34d399" : "1px solid #f87171",
              }}
              className="flex items-center gap-2 font-bold px-4 py-2.5 rounded-xl transition-all cursor-pointer shadow-lg text-sm"
            >
              <Power size={18} />
              <span>{adsEnabled ? "Pubs Activées (Global)" : "Pubs Désactivées (Masquées)"}</span>
            </button>

            <button
              onClick={() => setShowForm(!showForm)}
              style={{
                backgroundColor: "#e05a68",
                color: "#ffffff",
                border: "1px solid #c93f52",
              }}
              className="px-4 py-2.5 font-bold rounded-xl transition-all flex items-center gap-2 shadow-lg cursor-pointer text-sm"
            >
              <Plus size={18} /> <span>Nouvelle publicité</span>
            </button>
          </div>
        </div>

        {showForm && (
          <div className="card p-6 mb-6 animate-fade-in max-w-3xl border border-[#e05a68]/30 bg-[#12080b] rounded-2xl">
            <h3 className="font-bold mb-4 text-lg text-[#e05a68]">Créer une publicité</h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1.5">Titre de la campagne *</label>
                <input type="text" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} className="input text-sm" placeholder="Nom interne ou annonceur" required />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1.5">Emplacement *</label>
                <select value={form.placement} onChange={e => setForm({ ...form, placement: e.target.value })} className="input text-sm">
                  <option value="native">Publicité Native (Carte vidéo dans la grille)</option>
                  <option value="banner">Bannière accueil</option>
                  <option value="in-video">In-Video / Popunder Exoclick</option>
                  <option value="pre-roll">Avant vidéo (Pre-roll)</option>
                  <option value="mid-roll">Pendant vidéo (Mid-roll)</option>
                  <option value="between-photos">Entre les photos</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1.5">Image URL</label>
                <input type="url" value={form.imageUrl} onChange={e => setForm({ ...form, imageUrl: e.target.value })} className="input text-sm" placeholder="https://..." />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1.5">Lien URL de la cible</label>
                <input type="url" value={form.linkUrl} onChange={e => setForm({ ...form, linkUrl: e.target.value })} className="input text-sm" placeholder="https://..." />
              </div>
              <div className="flex gap-3 pt-2">
                <button type="submit" className="btn btn-primary">Créer l'annonce</button>
                <button type="button" onClick={() => setShowForm(false)} className="btn btn-outline">Annuler</button>
              </div>
            </form>
          </div>
        )}

        {loading ? (
          <div className="space-y-3">{[...Array(3)].map((_, i) => <div key={i} className="skeleton h-20 w-full" />)}</div>
        ) : ads.length === 0 ? (
          <div className="text-center py-16 card bg-[#12080b] rounded-2xl border border-white/5" style={{ color: "var(--text-muted)" }}>
            <Megaphone size={40} className="mx-auto mb-3 opacity-30" />
            <p className="font-bold text-sm">Aucune publicité classique enregistrée pour le moment.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {ads.map((ad) => (
              <div key={ad.id} className="card p-4 flex items-center justify-between gap-4 bg-[#12080b] border border-white/10 rounded-2xl">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-xl bg-white/5 flex items-center justify-center font-bold text-xs uppercase text-[#e05a68] border border-white/10">
                    {ad.placement.slice(0, 3)}
                  </div>
                  <div>
                    <h4 className="font-bold text-sm text-white">{ad.title}</h4>
                    <p className="text-xs text-[#a38890]">{ad.linkUrl || "Pas de lien"}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <button
                    onClick={() => toggleAdActive(ad.id, ad.isActive)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all ${
                      ad.isActive ? "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30" : "bg-red-500/20 text-red-400 border border-red-500/30"
                    }`}
                  >
                    {ad.isActive ? <CheckCircle size={14} /> : <XCircle size={14} />}
                    <span>{ad.isActive ? "Active" : "Inactive"}</span>
                  </button>
                  <button onClick={() => deleteAd(ad.id)} className="p-2 text-red-400 hover:bg-red-500/10 rounded-lg transition-colors">
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

    </div>
  );
}
