"use client";
import { useState, useEffect } from "react";
import { Plus, Trash2, Megaphone, CheckCircle, XCircle, Power } from "lucide-react";
import { toast } from "@/components/ui/Toaster";
import { formatNumber } from "@/lib/utils";

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">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-black mb-1">Publicités & Régies</h1>
            <span style={{ backgroundColor: "#f59e0b", color: "#000", padding: "4px 12px", borderRadius: "8px", fontWeight: "bold", fontSize: "12px" }}>
              TEST DE MISE A JOUR V2 OK ✅
            </span>
          </div>
          <p style={{ color: "var(--text-secondary)" }}>{ads.length} annonce(s) en base</p>
        </div>


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

          <button
            onClick={() => setShowForm(!showForm)}
            style={{
              backgroundColor: "#b57bee",
              color: "#000000",
              border: "1px solid #c992f5",
              opacity: 1,
            }}
            className="px-4 py-2.5 font-bold rounded-xl transition-all flex items-center gap-2 shadow-lg cursor-pointer"
          >
            <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-[#b57bee]/30">
          <h2 className="font-bold mb-4 text-lg text-[#b57bee]">Créer une publicité</h2>
          <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="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(4)].map((_, i) => <div key={i} className="skeleton h-20 w-full" />)}</div>
      ) : ads.length === 0 ? (
        <div className="text-center py-20 card" style={{ color: "var(--text-muted)" }}>
          <Megaphone size={48} className="mx-auto mb-4 opacity-30" />
          <p className="font-bold">Aucune publicité enregistrée pour le moment.</p>
        </div>
      ) : (
        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ borderBottom: "1px solid var(--border)", background: "var(--bg-secondary)" }}>
                {["Titre", "Emplacement", "Statut", "Vues", "Clics", "Actions"].map(h => (
                  <th key={h} className="text-left px-4 py-3 font-semibold text-xs uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {ads.map((ad, i) => (
                <tr key={ad.id} style={{ borderTop: i > 0 ? "1px solid var(--border)" : "none" }}>
                  <td className="px-4 py-3 font-bold">{ad.title}</td>
                  <td className="px-4 py-3"><span className="badge badge-free text-xs font-mono">{ad.placement}</span></td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() => toggleAdActive(ad.id, ad.isActive)}
                      className="flex items-center gap-1.5 text-xs font-bold transition-colors cursor-pointer hover:opacity-80"
                      title="Cliquer pour changer le statut"
                    >
                      {ad.isActive ? (
                        <span className="flex items-center gap-1 text-emerald-400 bg-emerald-500/10 px-2 py-1 rounded-full border border-emerald-500/20">
                          <CheckCircle size={14} /> Actif
                        </span>
                      ) : (
                        <span className="flex items-center gap-1 text-red-400 bg-red-500/10 px-2 py-1 rounded-full border border-red-500/20">
                          <XCircle size={14} /> Inactif
                        </span>
                      )}
                    </button>
                  </td>
                  <td className="px-4 py-3 font-mono" style={{ color: "var(--text-secondary)" }}>{formatNumber(ad.impressions || 0)}</td>
                  <td className="px-4 py-3 font-mono" style={{ color: "var(--text-secondary)" }}>{formatNumber(ad.clicks || 0)}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => deleteAd(ad.id)} className="btn btn-ghost w-8 h-8 rounded-lg p-0 flex items-center justify-center text-red-500 hover:bg-red-500/10">
                      <Trash2 size={16} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

