"use client";

import { useEffect, useState } from "react";
import { Plus, Edit, Trash2, Check, X, Calendar, Link as LinkIcon, Palette } from "lucide-react";

interface PromoBanner {
  id: string;
  text: string;
  cta_text?: string | null;
  cta_link?: string | null;
  countdown_enabled: boolean;
  countdown_end_date?: string | null;
  gradient_from: string;
  gradient_to: string;
  text_color: string;
  cta_bg_color: string;
  cta_text_color: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

const GRADIENT_PRESETS = [
  { from: "slate-100", to: "slate-200", label: "Gris clair" },
  { from: "indigo-100", to: "purple-100", label: "Indigo clair → Violet clair" },
  { from: "blue-50", to: "cyan-100", label: "Bleu clair → Cyan clair" },
  { from: "purple-50", to: "pink-100", label: "Violet clair → Rose clair" },
  { from: "orange-50", to: "amber-100", label: "Orange clair → Ambre clair" },
  { from: "green-50", to: "teal-100", label: "Vert clair → Turquoise clair" },
];

const TEXT_COLOR_OPTIONS = [
  { value: "slate-800", label: "Gris foncé", hex: "#1e293b" },
  { value: "slate-900", label: "Gris très foncé", hex: "#0f172a" },
  { value: "white", label: "Blanc", hex: "#ffffff" },
  { value: "indigo-900", label: "Indigo foncé", hex: "#312e81" },
  { value: "purple-900", label: "Violet foncé", hex: "#581c87" },
];

const CTA_BG_COLOR_OPTIONS = [
  { value: "#efc543", label: "Jaune Odentas", hex: "#efc543" },
  { value: "#1e293b", label: "Gris foncé", hex: "#1e293b" },
  { value: "#0f172a", label: "Gris très foncé", hex: "#0f172a" },
  { value: "#ffffff", label: "Blanc", hex: "#ffffff" },
  { value: "#312e81", label: "Indigo foncé", hex: "#312e81" },
  { value: "#581c87", label: "Violet foncé", hex: "#581c87" },
];

const CTA_TEXT_COLOR_OPTIONS = [
  { value: "slate-900", label: "Gris très foncé", hex: "#0f172a" },
  { value: "white", label: "Blanc", hex: "#ffffff" },
  { value: "slate-800", label: "Gris foncé", hex: "#1e293b" },
];

export default function OffresPromoClient() {
  const [banners, setBanners] = useState<PromoBanner[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  
  // Form state
  const [formData, setFormData] = useState({
    text: "",
    cta_text: "",
    cta_link: "",
    countdown_enabled: false,
    countdown_end_date: "",
    gradient_from: "indigo-600",
    gradient_to: "purple-600",
    text_color: "slate-800",
    cta_bg_color: "#efc543",
    cta_text_color: "slate-900",
    is_active: false,
  });

  const fetchBanners = async () => {
    try {
      const res = await fetch("/api/promo-banners", { 
        credentials: "include",
        cache: "no-store" 
      });
      if (!res.ok) throw new Error("Erreur fetch");
      
      const data = await res.json();
      setBanners(data.banners || []);
    } catch (err) {
      console.error("Erreur lors du chargement des bannières:", err);
    } finally {
      setLoading(false);
    }
  };

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

  const resetForm = () => {
    setFormData({
      text: "",
      cta_text: "",
      cta_link: "",
      countdown_enabled: false,
      countdown_end_date: "",
      gradient_from: "slate-100",
      gradient_to: "slate-200",
      text_color: "slate-800",
      cta_bg_color: "#efc543",
      cta_text_color: "slate-900",
      is_active: false,
    });
    setEditingId(null);
    setShowForm(false);
  };

  const handleEdit = (banner: PromoBanner) => {
    setFormData({
      text: banner.text,
      cta_text: banner.cta_text || "",
      cta_link: banner.cta_link || "",
      countdown_enabled: banner.countdown_enabled,
      countdown_end_date: banner.countdown_end_date 
        ? new Date(banner.countdown_end_date).toISOString().slice(0, 16)
        : "",
      gradient_from: banner.gradient_from,
      gradient_to: banner.gradient_to,
      text_color: banner.text_color || "slate-800",
      cta_bg_color: banner.cta_bg_color || "#efc543",
      cta_text_color: banner.cta_text_color || "slate-900",
      is_active: banner.is_active,
    });
    setEditingId(banner.id);
    setShowForm(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const payload = {
      ...formData,
      countdown_end_date: formData.countdown_enabled && formData.countdown_end_date
        ? new Date(formData.countdown_end_date).toISOString()
        : null,
    };

    try {
      if (editingId) {
        // Mise à jour
        const res = await fetch("/api/promo-banners", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify({ id: editingId, ...payload }),
        });
        
        if (!res.ok) throw new Error("Erreur mise à jour");
      } else {
        // Création
        const res = await fetch("/api/promo-banners", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify(payload),
        });
        
        if (!res.ok) throw new Error("Erreur création");
      }
      
      await fetchBanners();
      resetForm();
    } catch (err) {
      console.error("Erreur lors de la sauvegarde:", err);
      alert("Erreur lors de la sauvegarde");
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Êtes-vous sûr de vouloir supprimer cette bannière ?")) return;
    
    try {
      const res = await fetch(`/api/promo-banners?id=${id}`, {
        method: "DELETE",
        credentials: "include",
      });
      
      if (!res.ok) throw new Error("Erreur suppression");
      
      await fetchBanners();
    } catch (err) {
      console.error("Erreur lors de la suppression:", err);
      alert("Erreur lors de la suppression");
    }
  };

  const toggleActive = async (banner: PromoBanner) => {
    try {
      const res = await fetch("/api/promo-banners", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ 
          id: banner.id, 
          is_active: !banner.is_active 
        }),
      });
      
      if (!res.ok) throw new Error("Erreur activation");
      
      await fetchBanners();
    } catch (err) {
      console.error("Erreur lors de l'activation:", err);
      alert("Erreur lors de l'activation");
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <p className="text-sm text-slate-600">Chargement...</p>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Offres promo</h1>
          <p className="text-sm text-slate-600 mt-1">
            Gérez les bannières promotionnelles affichées en haut de l'espace paie
          </p>
        </div>
        
        <button
          onClick={() => setShowForm(true)}
          className="inline-flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition"
        >
          <Plus className="w-4 h-4" />
          Nouvelle bannière
        </button>
      </div>

      {/* Formulaire */}
      {showForm && (
        <div className="bg-white rounded-xl border p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-slate-900">
              {editingId ? "Modifier la bannière" : "Nouvelle bannière"}
            </h2>
            <button
              onClick={resetForm}
              className="text-slate-400 hover:text-slate-600"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Texte principal */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">
                Texte de la bannière
              </label>
              <input
                type="text"
                value={formData.text}
                onChange={(e) => setFormData({ ...formData, text: e.target.value })}
                required
                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                placeholder="Ex: Offre spéciale - 20% de réduction jusqu'à la fin du mois !"
              />
            </div>

            {/* CTA */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Texte du bouton (optionnel)
                </label>
                <input
                  type="text"
                  value={formData.cta_text}
                  onChange={(e) => setFormData({ ...formData, cta_text: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="Ex: En savoir plus"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Lien du bouton (optionnel)
                </label>
                <input
                  type="url"
                  value={formData.cta_link}
                  onChange={(e) => setFormData({ ...formData, cta_link: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  placeholder="https://..."
                />
              </div>
            </div>

            {/* Compte à rebours */}
            <div className="space-y-2">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={formData.countdown_enabled}
                  onChange={(e) => setFormData({ ...formData, countdown_enabled: e.target.checked })}
                  className="rounded text-indigo-600 focus:ring-indigo-500"
                />
                <span className="text-sm font-medium text-slate-700">
                  Activer le compte à rebours
                </span>
              </label>
              
              {formData.countdown_enabled && (
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    Date de fin
                  </label>
                  <input
                    type="datetime-local"
                    value={formData.countdown_end_date}
                    onChange={(e) => setFormData({ ...formData, countdown_end_date: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  />
                </div>
              )}
            </div>

            {/* Gradient */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Couleur de fond (gradient)
              </label>
              <div className="grid grid-cols-3 gap-2">
                {GRADIENT_PRESETS.map((preset) => (
                  <button
                    key={`${preset.from}-${preset.to}`}
                    type="button"
                    onClick={() => setFormData({ 
                      ...formData, 
                      gradient_from: preset.from, 
                      gradient_to: preset.to 
                    })}
                    className={`p-3 rounded-lg border-2 transition ${
                      formData.gradient_from === preset.from && formData.gradient_to === preset.to
                        ? "border-indigo-600"
                        : "border-slate-200 hover:border-slate-300"
                    }`}
                  >
                    <div className={`h-8 rounded bg-gradient-to-r from-${preset.from} to-${preset.to} mb-1`} />
                    <p className="text-xs text-slate-600">{preset.label}</p>
                  </button>
                ))}
              </div>
            </div>

            {/* Couleur du texte */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Couleur du texte
              </label>
              <div className="grid grid-cols-5 gap-2">
                {TEXT_COLOR_OPTIONS.map((option) => (
                  <button
                    key={option.value}
                    type="button"
                    onClick={() => setFormData({ ...formData, text_color: option.value })}
                    className={`p-3 rounded-lg border-2 transition ${
                      formData.text_color === option.value
                        ? "border-indigo-600"
                        : "border-slate-200 hover:border-slate-300"
                    }`}
                  >
                    <div 
                      className="h-8 rounded mb-1" 
                      style={{ backgroundColor: option.hex }}
                    />
                    <p className="text-xs text-slate-600">{option.label}</p>
                  </button>
                ))}
              </div>
            </div>

            {/* Couleur du bouton CTA */}
            {formData.cta_text && formData.cta_link && (
              <>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-2">
                    Couleur de fond du bouton CTA
                  </label>
                  <div className="grid grid-cols-6 gap-2">
                    {CTA_BG_COLOR_OPTIONS.map((option) => (
                      <button
                        key={option.value}
                        type="button"
                        onClick={() => setFormData({ ...formData, cta_bg_color: option.value })}
                        className={`p-3 rounded-lg border-2 transition ${
                          formData.cta_bg_color === option.value
                            ? "border-indigo-600"
                            : "border-slate-200 hover:border-slate-300"
                        }`}
                      >
                        <div 
                          className="h-8 rounded mb-1" 
                          style={{ backgroundColor: option.hex }}
                        />
                        <p className="text-xs text-slate-600">{option.label}</p>
                      </button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-2">
                    Couleur du texte du bouton CTA
                  </label>
                  <div className="grid grid-cols-3 gap-2">
                    {CTA_TEXT_COLOR_OPTIONS.map((option) => (
                      <button
                        key={option.value}
                        type="button"
                        onClick={() => setFormData({ ...formData, cta_text_color: option.value })}
                        className={`p-3 rounded-lg border-2 transition ${
                          formData.cta_text_color === option.value
                            ? "border-indigo-600"
                            : "border-slate-200 hover:border-slate-300"
                        }`}
                      >
                        <div 
                          className="h-8 rounded mb-1" 
                          style={{ backgroundColor: option.hex }}
                        />
                        <p className="text-xs text-slate-600">{option.label}</p>
                      </button>
                    ))}
                  </div>
                </div>
              </>
            )}

            {/* Prévisualisation */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Aperçu
              </label>
              <div 
                className={`py-3 px-4 rounded-lg bg-gradient-to-r from-${formData.gradient_from} to-${formData.gradient_to}`}
                style={{ 
                  background: `linear-gradient(to right, var(--tw-gradient-from), var(--tw-gradient-to))` 
                }}
              >
                <div className="flex items-center justify-between gap-4">
                  <p className={`text-sm font-medium text-${formData.text_color}`}>
                    {formData.text || "Votre texte ici..."}
                  </p>
                  {formData.cta_text && (
                    <span 
                      className={`inline-flex items-center gap-2 px-3 py-1 rounded-lg text-sm font-semibold text-${formData.cta_text_color}`}
                      style={{ backgroundColor: formData.cta_bg_color }}
                    >
                      {formData.cta_text}
                    </span>
                  )}
                </div>
              </div>
            </div>

            {/* Activation */}
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={formData.is_active}
                onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                className="rounded text-indigo-600 focus:ring-indigo-500"
              />
              <span className="text-sm font-medium text-slate-700">
                Activer cette bannière immédiatement
              </span>
            </label>

            {/* Actions */}
            <div className="flex items-center gap-3 pt-4 border-t">
              <button
                type="submit"
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition"
              >
                {editingId ? "Mettre à jour" : "Créer"}
              </button>
              <button
                type="button"
                onClick={resetForm}
                className="px-4 py-2 border rounded-lg hover:bg-slate-50 transition"
              >
                Annuler
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Liste des bannières */}
      <div className="space-y-3">
        {banners.length === 0 ? (
          <div className="bg-white rounded-xl border p-6 text-center">
            <p className="text-sm text-slate-600">Aucune bannière créée pour le moment</p>
          </div>
        ) : (
          banners.map((banner) => (
            <div
              key={banner.id}
              className="bg-white rounded-xl border p-4"
            >
              <div className="flex items-start justify-between gap-4">
                {/* Contenu */}
                <div className="flex-1 space-y-2">
                  <div className="flex items-center gap-3">
                    <h3 className="font-medium text-slate-900">{banner.text}</h3>
                    {banner.is_active && (
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-green-100 text-green-700 text-xs font-medium rounded-full">
                        <Check className="w-3 h-3" />
                        Active
                      </span>
                    )}
                  </div>
                  
                  <div className="flex items-center gap-4 text-xs text-slate-500">
                    {banner.cta_text && banner.cta_link && (
                      <span className="inline-flex items-center gap-1">
                        <LinkIcon className="w-3 h-3" />
                        CTA: {banner.cta_text}
                      </span>
                    )}
                    {banner.countdown_enabled && banner.countdown_end_date && (
                      <span className="inline-flex items-center gap-1">
                        <Calendar className="w-3 h-3" />
                        Fin: {new Date(banner.countdown_end_date).toLocaleString("fr-FR")}
                      </span>
                    )}
                    <span className="inline-flex items-center gap-1">
                      <Palette className="w-3 h-3" />
                      {banner.gradient_from} → {banner.gradient_to}
                    </span>
                  </div>

                  {/* Aperçu miniature */}
                  <div className={`bg-gradient-to-r from-${banner.gradient_from} to-${banner.gradient_to} text-white py-2 px-3 rounded text-xs`}>
                    {banner.text}
                  </div>
                </div>

                {/* Actions */}
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => toggleActive(banner)}
                    className={`p-2 rounded-lg transition ${
                      banner.is_active
                        ? "bg-green-100 text-green-700 hover:bg-green-200"
                        : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                    }`}
                    title={banner.is_active ? "Désactiver" : "Activer"}
                  >
                    {banner.is_active ? <X className="w-4 h-4" /> : <Check className="w-4 h-4" />}
                  </button>
                  
                  <button
                    onClick={() => handleEdit(banner)}
                    className="p-2 bg-slate-100 text-slate-600 rounded-lg hover:bg-slate-200 transition"
                    title="Modifier"
                  >
                    <Edit className="w-4 h-4" />
                  </button>
                  
                  <button
                    onClick={() => handleDelete(banner.id)}
                    className="p-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition"
                    title="Supprimer"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
