"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Award, Phone, Sparkles, AlertCircle } from "lucide-react";
import { useSiteSettings } from "@/components/SettingsProvider";

export default function PromoCardPublicPage() {
  const router = useRouter();
  const { enable_promocard } = useSiteSettings();
  const [phone, setPhone] = useState("");
  const [status, setStatus] = useState<any | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!enable_promocard) {
      router.replace("/");
    }
  }, [enable_promocard, router]);

  if (!enable_promocard) {
    return null;
  }

  const handleCheck = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    setStatus(null);

    try {
      const cleanPhone = phone.replace(/\D/g, "");
      const res = await fetch(`/api/promocard/status?phone=${encodeURIComponent(cleanPhone)}`);
      const data = await res.json();

      if (data.success) {
        setStatus(data);
      } else {
        setMessage(data.message || "Usuario no encontrado.");
      }
    } catch {
      setMessage("Error al consultar la tarjeta. Intenta nuevamente.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-xl mx-auto px-6 sm:px-8 py-20 md:py-28 space-y-10 bg-[#F7F5F0]">
      <div className="text-center space-y-3">
        <span className="inline-flex items-center gap-1.5 px-3.5 py-1 rounded-[6px] text-xs font-black bg-[#67d2f2] text-[#083F78] uppercase tracking-wider font-artisan-sans">
          <Award size={14} />
          <span>Fidelización Artesanal</span>
        </span>
        <h1 className="text-3xl sm:text-5xl font-artisan-serif font-bold text-[#083F78] tracking-tight">
          Tu Tarjeta PromoCard
        </h1>
        <p className="text-xs sm:text-sm text-[#2b394a]/80 font-artisan-sans leading-relaxed">
          Ingresa tu número celular registrado para consultar cuántos pedidos te faltan para tu pizza artesanal gratis.
        </p>
      </div>

      <div className="bg-white border border-[#a1a39e]/20 rounded-[8px] p-8 sm:p-10 space-y-7">
        <form onSubmit={handleCheck} className="space-y-5 font-artisan-sans">
          <div>
            <label className="block text-xs font-bold text-[#083F78] uppercase tracking-wider mb-2">
              Número de Celular
            </label>
            <div className="relative">
              <Phone size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#a1a39e]" />
              <input
                type="tel"
                placeholder="Ej. 3001526282"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="w-full bg-[#F7F5F0] border border-[#a1a39e]/30 rounded-[8px] py-3 pl-10 pr-4 text-base font-mono text-[#083F78] focus:outline-none focus:border-[#67d2f2]"
                required
              />
            </div>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black py-3.5 rounded-[8px] text-xs uppercase tracking-wider transition disabled:opacity-50 shadow-md shadow-[#ffc324]/20"
          >
            {loading ? "Consultando..." : "Consultar Mis Puntos"}
          </button>
        </form>

        {message && (
          <div className="p-4 bg-white border border-[#a1a39e]/30 rounded-[8px] text-[#083F78] text-xs sm:text-sm flex items-center gap-2.5 font-artisan-sans">
            <AlertCircle size={18} className="text-[#67d2f2] shrink-0" />
            <span>{message}</span>
          </div>
        )}

        {status && (
          <div className="bg-[#083F78] text-[#F7F5F0] rounded-[8px] p-7 space-y-6 animate-in fade-in duration-300">
            <div className="flex items-center justify-between border-b border-white/10 pb-4">
              <div>
                <span className="text-[11px] font-black text-[#67d2f2] uppercase tracking-widest block font-artisan-sans">
                  Cliente Sanlore Pizza
                </span>
                <h3 className="text-2xl font-artisan-serif font-bold text-white">{status.customer_name || "Cliente Fiel"}</h3>
              </div>
              <div className="w-11 h-11 bg-[#67d2f2] text-[#083F78] rounded-[6px] flex items-center justify-center font-bold">
                <Award size={22} />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 text-center font-artisan-sans">
              <div className="bg-white/5 border border-white/10 p-5 rounded-[8px]">
                <span className="text-[11px] text-[#a1a39e] uppercase tracking-wider block">Compras Restantes</span>
                <span className="text-3xl font-mono font-bold text-[#67d2f2] mt-1 block">{status.points_remaining}</span>
                <span className="text-[10px] text-[#a1a39e] block mt-1">de 10 compras</span>
              </div>

              <div className="bg-white/5 border border-white/10 p-5 rounded-[8px]">
                <span className="text-[11px] text-[#a1a39e] uppercase tracking-wider block">Pizzas Disponibles</span>
                <span className="text-3xl font-mono font-bold text-white mt-1 block">
                  {status.total_earned - status.total_claimed}
                </span>
                <span className="text-[10px] text-[#a1a39e] block mt-1">listas para redimir</span>
              </div>
            </div>

            <div className="text-xs text-[#a1a39e] text-center border-t border-white/10 pt-4 font-artisan-sans">
              Total de pizzas gratis ganadas con PromoCard:{" "}
              <strong className="text-white font-bold">{status.total_earned}</strong>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
