"use client";

import React, { useState, useEffect } from "react";
import { Plus, Edit2, Trash2, Tag, CheckCircle, XCircle } from "lucide-react";
import { Promo } from "@/types";

export default function AdminPromosPage() {
  const [promos, setPromos] = useState<Promo[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingPromo, setEditingPromo] = useState<Promo | null>(null);

  // Form inputs
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [link, setLink] = useState("");
  const [isHome, setIsHome] = useState(true);
  const [isActive, setIsActive] = useState(true);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const fetchPromos = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/promos?all=true");
      const data = await res.json();
      setPromos(data || []);
    } catch (err) {
      console.error("Error loading promos:", err);
    } finally {
      setLoading(false);
    }
  };

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

  const openCreateModal = () => {
    setEditingPromo(null);
    setTitle("");
    setDescription("");
    setLink("");
    setIsHome(true);
    setIsActive(true);
    setImageFile(null);
    setModalOpen(true);
  };

  const openEditModal = (p: Promo) => {
    setEditingPromo(p);
    setTitle(p.title);
    setDescription(p.description || "");
    setLink(p.link || "");
    setIsHome(Boolean(p.is_home));
    setIsActive(Boolean(p.is_active));
    setImageFile(null);
    setModalOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);

    const formData = new FormData();
    formData.append("title", title);
    formData.append("description", description);
    formData.append("link", link);
    formData.append("is_home", isHome ? "1" : "0");
    formData.append("is_active", isActive ? "1" : "0");
    if (imageFile) {
      formData.append("image", imageFile);
    }

    try {
      const url = editingPromo ? `/api/promos/${editingPromo.id}` : "/api/promos";
      const method = editingPromo ? "PUT" : "POST";

      const res = await fetch(url, {
        method,
        body: formData
      });

      if (!res.ok) throw new Error("Error al guardar la promoción");

      setModalOpen(false);
      fetchPromos();
    } catch (err: any) {
      alert(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("¿Seguro que deseas eliminar esta promoción?")) return;
    try {
      const res = await fetch(`/api/promos/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Error al eliminar");
      fetchPromos();
    } catch (err: any) {
      alert(err.message);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-slate-900 tracking-tight">Promociones</h1>
          <p className="text-sm text-slate-500 mt-0.5">
            Configura combos, ofertas 2x1 y banners destacados de Sanlore Pizza.
          </p>
        </div>
        <button
          onClick={openCreateModal}
          className="inline-flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-slate-950 font-bold px-4 py-2.5 rounded-xl shadow-sm text-sm transition"
        >
          <Plus size={18} />
          <span>Crear Promoción</span>
        </button>
      </div>

      {/* Promos Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {loading ? (
          <div className="col-span-3 text-center py-12 text-slate-400">
            Cargando promociones...
          </div>
        ) : promos.length === 0 ? (
          <div className="col-span-3 text-center py-12 text-slate-400">
            No hay promociones registradas aún.
          </div>
        ) : (
          promos.map((p) => (
            <div
              key={p.id}
              className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm flex flex-col justify-between"
            >
              <div>
                {p.image ? (
                  <img
                    src={p.image}
                    alt={p.title}
                    className="w-full h-40 object-cover border-b border-slate-100"
                  />
                ) : (
                  <div className="w-full h-40 bg-slate-100 flex items-center justify-center text-slate-400">
                    <Tag size={32} />
                  </div>
                )}
                <div className="p-4">
                  <div className="flex items-center justify-between gap-2 mb-1">
                    <span
                      className={`text-[10px] font-bold px-2 py-0.5 rounded-full uppercase ${
                        Boolean(p.is_home)
                          ? "bg-amber-100 text-amber-800"
                          : "bg-slate-100 text-slate-600"
                      }`}
                    >
                      {Boolean(p.is_home) ? "En Portada" : "Solo en Promos"}
                    </span>
                    <span
                      className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                        Boolean(p.is_active)
                          ? "bg-emerald-100 text-emerald-800"
                          : "bg-rose-100 text-rose-800"
                      }`}
                    >
                      {Boolean(p.is_active) ? "Activa" : "Inactiva"}
                    </span>
                  </div>
                  <h3 className="font-bold text-slate-900 text-base">{p.title}</h3>
                  <p className="text-xs text-slate-500 mt-1 line-clamp-2">
                    {p.description || "Sin descripción"}
                  </p>
                </div>
              </div>

              <div className="p-4 pt-0 border-t border-slate-100 mt-3 flex justify-end gap-2">
                <button
                  onClick={() => openEditModal(p)}
                  className="p-2 text-slate-600 hover:text-amber-600 hover:bg-slate-100 rounded-lg transition"
                >
                  <Edit2 size={16} />
                </button>
                <button
                  onClick={() => handleDelete(p.id)}
                  className="p-2 text-slate-600 hover:text-rose-600 hover:bg-slate-100 rounded-lg transition"
                >
                  <Trash2 size={16} />
                </button>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Modal Add / Edit */}
      {modalOpen && (
        <div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-black text-slate-900 mb-1">
              {editingPromo ? "Editar Promoción" : "Nueva Promoción"}
            </h3>
            <p className="text-xs text-slate-500 mb-4">
              Configura los detalles de la oferta para clientes.
            </p>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Título de la Promo</label>
                <input
                  type="text"
                  placeholder="Ej. Martes de 2x1 en Pizzas Medianas"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  className="w-full border border-slate-300 rounded-xl p-2.5 text-sm"
                  required
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Descripción</label>
                <textarea
                  placeholder="Ej. Pide dos pizzas medianas al precio de una para domicilio en Galicia y Pereira."
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  className="w-full border border-slate-300 rounded-xl p-2.5 text-sm h-20"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Enlace / WhatsApp (Opcional)</label>
                <input
                  type="text"
                  placeholder="Dejar vacío para usar el WhatsApp automático de pedidos"
                  value={link}
                  onChange={(e) => setLink(e.target.value)}
                  className="w-full border border-slate-300 rounded-xl p-2.5 text-sm font-mono text-xs"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">Imagen del Banner</label>
                <input
                  type="file"
                  accept="image/*"
                  onChange={(e) => setImageFile(e.target.files?.[0] || null)}
                  className="w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-xs file:font-semibold file:bg-slate-100 file:text-slate-700 hover:file:bg-slate-200"
                />
              </div>

              <div className="flex gap-4 pt-2">
                <label className="flex items-center gap-2 text-sm text-slate-700 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={isHome}
                    onChange={(e) => setIsHome(e.target.checked)}
                    className="w-4 h-4 text-amber-500 rounded"
                  />
                  <span>Mostrar en Portada</span>
                </label>

                <label className="flex items-center gap-2 text-sm text-slate-700 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={isActive}
                    onChange={(e) => setIsActive(e.target.checked)}
                    className="w-4 h-4 text-emerald-500 rounded"
                  />
                  <span>Activa</span>
                </label>
              </div>

              <div className="flex gap-2 pt-4">
                <button
                  type="button"
                  onClick={() => setModalOpen(false)}
                  className="flex-1 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold py-2.5 rounded-xl text-sm transition"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="flex-1 bg-amber-500 hover:bg-amber-600 text-slate-950 font-bold py-2.5 rounded-xl text-sm transition"
                >
                  {submitting ? "Guardando..." : "Guardar Promoción"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

