"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { QrCode, RefreshCw, Printer, CheckCircle, Clock, Search, ToggleLeft, ToggleRight, Download } from "lucide-react";

type Product = {
  id: string;
  name: string;
  description: string;
  price: number;
  ticketCount: number;
  stock: number;
  isLimited: boolean;
};

type Registration = {
  id: string;
  correlativeNum: number;
  name: string;
  phone: string;
  email: string;
  status: "PENDING" | "PROCESSING" | "PAID";
  orderId: string | null;
  createdAt: string;
};

type ProcessResult = {
  orderId: string;
  correlativeNum: number;
  customerName: string;
  customerEmail: string;
  customerPhone: string;
  productName: string;
  productPrice: number;
  ticketCount: number;
  tickets: string[];
  emailError?: string;
};

export default function AdminStandClient({
  initialStandEnabled,
  products,
}: {
  initialStandEnabled: boolean;
  products: Product[];
}) {
  const [standEnabled, setStandEnabled] = useState(initialStandEnabled);
  const [togglingStand, setTogglingStand] = useState(false);

  const [registrations, setRegistrations] = useState<Registration[]>([]);
  const [loadingList, setLoadingList] = useState(false);

  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
  const [registrationUrl, setRegistrationUrl] = useState<string>("");
  const [loadingQr, setLoadingQr] = useState(false);

  const [search, setSearch] = useState("");

  // Modal de pago
  const [selectedReg, setSelectedReg] = useState<Registration | null>(null);
  const [selectedProductId, setSelectedProductId] = useState("");
  const [processing, setProcessing] = useState(false);
  const [processError, setProcessError] = useState<string | null>(null);

  // Resultado del proceso → recibo de impresión
  const [receipt, setReceipt] = useState<ProcessResult | null>(null);

  const receiptRef = useRef<HTMLDivElement>(null);

  // ── Cargar registros ─────────────────────────────────────────────────────
  const loadRegistrations = useCallback(async () => {
    setLoadingList(true);
    try {
      const res = await fetch("/api/admin/stand/registrations");
      const data = await res.json();
      if (data.registrations) setRegistrations(data.registrations);
    } catch {
      // silencioso
    } finally {
      setLoadingList(false);
    }
  }, []);

  // ── Cargar QR ────────────────────────────────────────────────────────────
  const loadQr = useCallback(async () => {
    setLoadingQr(true);
    try {
      const res = await fetch("/api/admin/stand/qr");
      const data = await res.json();
      if (data.qrDataUrl) {
        setQrDataUrl(data.qrDataUrl);
        setRegistrationUrl(data.registrationUrl);
      }
    } catch {
      // silencioso
    } finally {
      setLoadingQr(false);
    }
  }, []);

  useEffect(() => {
    loadRegistrations();
    loadQr();
  }, [loadRegistrations, loadQr]);

  // ── Toggle stand ─────────────────────────────────────────────────────────
  async function handleToggleStand() {
    setTogglingStand(true);
    const newVal = !standEnabled;
    try {
      const res = await fetch("/api/admin/site-config", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ stand_enabled: newVal ? "true" : "false" }),
      });
      if (res.ok) setStandEnabled(newVal);
    } catch {
      // silencioso
    } finally {
      setTogglingStand(false);
    }
  }

  // ── Procesar pago ─────────────────────────────────────────────────────────
  async function handleProcess() {
    if (!selectedReg || !selectedProductId) return;
    setProcessError(null);
    setProcessing(true);
    try {
      const res = await fetch(
        `/api/admin/stand/registrations/${selectedReg.id}/process`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ productId: selectedProductId }),
        }
      );
      const data = await res.json();
      if (!res.ok) {
        setProcessError(data.error ?? "Error al procesar.");
        return;
      }
      setReceipt(data);
      setSelectedReg(null);
      setSelectedProductId("");
      await loadRegistrations();
    } catch {
      setProcessError("Error de conexión.");
    } finally {
      setProcessing(false);
    }
  }

  // ── Imprimir recibo ───────────────────────────────────────────────────────
  function handlePrint() {
    window.print();
  }

  // ── Descargar QR ─────────────────────────────────────────────────────────
  function handleDownloadQr() {
    if (!qrDataUrl) return;
    const a = document.createElement("a");
    a.href = qrDataUrl;
    a.download = "qr-stand-registro.png";
    a.click();
  }

  // ── Filtrado ──────────────────────────────────────────────────────────────
  const filtered = registrations.filter((r) => {
    if (!search.trim()) return true;
    const q = search.toLowerCase();
    return (
      r.name.toLowerCase().includes(q) ||
      r.email.toLowerCase().includes(q) ||
      r.phone.includes(q) ||
      String(r.correlativeNum).includes(q)
    );
  });

  const pending = filtered.filter((r) => r.status === "PENDING" || r.status === "PROCESSING");
  const paid = filtered.filter((r) => r.status === "PAID");

  const formatPrice = (p: number) =>
    new Intl.NumberFormat("es-CL", { style: "currency", currency: "CLP" }).format(p);

  const formatDate = (d: string) =>
    new Intl.DateTimeFormat("es-CL", {
      day: "2-digit",
      month: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(d));

  // ── Recibo de impresión ───────────────────────────────────────────────────
  if (receipt) {
    const now = new Date();
    const dateStr = new Intl.DateTimeFormat("es-CL", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    }).format(now);

    return (
      <>
        {/* Estilos solo para impresión */}
        <style>{`
          @media print {
            body * { visibility: hidden !important; }
            #thermal-receipt, #thermal-receipt * { visibility: visible !important; }
            #thermal-receipt {
              position: fixed !important;
              top: 0 !important;
              left: 0 !important;
              width: 80mm !important;
              margin: 0 !important;
              padding: 0 !important;
            }
            .no-print { display: none !important; }
          }
        `}</style>

        {/* Pantalla de éxito (no se imprime) */}
        <div className="no-print p-6 max-w-lg mx-auto">
          <div className="bg-green-500/10 border border-green-500/30 rounded-2xl p-6 mb-6">
            <div className="flex items-center gap-3 mb-4">
              <CheckCircle className="w-8 h-8 text-green-400 shrink-0" />
              <div>
                <h2 className="text-xl font-black text-white">¡Pago procesado!</h2>
                <p className="text-green-300 text-sm">Tickets generados y correo enviado</p>
              </div>
            </div>
            <div className="space-y-1 text-sm text-gray-300">
              <p><span className="text-gray-500">Cliente:</span> {receipt.customerName}</p>
              <p><span className="text-gray-500">Email:</span> {receipt.customerEmail}</p>
              <p><span className="text-gray-500">Pack:</span> {receipt.productName}</p>
              <p><span className="text-gray-500">Tickets:</span> {receipt.tickets.length}</p>
            </div>
          </div>

          {receipt.emailError && (
            <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-xl p-4 mb-4 text-yellow-300 text-sm">
              ⚠️ El correo no pudo enviarse: {receipt.emailError}. Los tickets fueron creados igualmente.
            </div>
          )}

          <div className="flex gap-3">
            <button
              onClick={handlePrint}
              className="flex-1 flex items-center justify-center gap-2 bg-[#0ea5c6] hover:bg-[#c9a227] text-black font-bold py-3 px-4 rounded-xl transition"
            >
              <Printer className="w-5 h-5" />
              Imprimir recibo
            </button>
            <button
              onClick={() => setReceipt(null)}
              className="flex-1 bg-white/10 hover:bg-white/20 text-white font-semibold py-3 px-4 rounded-xl transition"
            >
              Volver al stand
            </button>
          </div>
        </div>

        {/* Recibo térmico (solo para impresora) */}
        <div
          id="thermal-receipt"
          ref={receiptRef}
          style={{
            fontFamily: "monospace",
            fontSize: "12px",
            width: "80mm",
            maxWidth: "80mm",
            padding: "8px",
            color: "#000",
            background: "#fff",
            lineHeight: "1.5",
          }}
        >
          <div style={{ textAlign: "center", borderBottom: "1px dashed #000", paddingBottom: "8px", marginBottom: "8px" }}>
            <div style={{ fontSize: "16px", fontWeight: "900", letterSpacing: "2px" }}>CONCURSANDO CON AMOR</div>
            <div style={{ fontSize: "10px" }}>SORTEO PRESENCIAL</div>
            <div style={{ fontSize: "10px" }}>{dateStr}</div>
          </div>

          <div style={{ marginBottom: "8px" }}>
            <div><strong>Cliente:</strong> {receipt.customerName}</div>
            <div><strong>Telefono:</strong> {receipt.customerPhone}</div>
            <div><strong>Email:</strong> {receipt.customerEmail}</div>
            <div><strong>Turno N°:</strong> #{receipt.correlativeNum}</div>
          </div>

          <div style={{ borderTop: "1px dashed #000", borderBottom: "1px dashed #000", padding: "6px 0", marginBottom: "8px" }}>
            <div><strong>Pack:</strong> {receipt.productName}</div>
            <div><strong>Precio:</strong> {formatPrice(receipt.productPrice)}</div>
            <div><strong>Pagado con:</strong> POS / Terminal</div>
          </div>

          <div style={{ marginBottom: "8px" }}>
            <div style={{ fontWeight: "bold", marginBottom: "4px" }}>
              CODIGOS DE SORTEO ({receipt.tickets.length}):
            </div>
            {receipt.tickets.map((t) => (
              <div key={t} style={{ fontWeight: "bold", letterSpacing: "1px", fontSize: "13px" }}>
                {t}
              </div>
            ))}
          </div>

          <div style={{ borderTop: "1px dashed #000", paddingTop: "6px", textAlign: "center", fontSize: "10px" }}>
            <div>Guarda este recibo como comprobante</div>
            <div>de tu participacion en el sorteo.</div>
            <div style={{ marginTop: "4px" }}>Orden: {receipt.orderId.slice(0, 16)}</div>
          </div>
        </div>
      </>
    );
  }

  return (
    <div className="space-y-6">
      {/* Título */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-black text-white">Stand Presencial</h1>
          <p className="text-gray-400 text-sm mt-0.5">Cobro vía POS · Gestión de turnos del evento</p>
        </div>
        <button
          onClick={loadRegistrations}
          disabled={loadingList}
          className="flex items-center gap-2 text-gray-400 hover:text-white transition text-sm"
        >
          <RefreshCw className={`w-4 h-4 ${loadingList ? "animate-spin" : ""}`} />
          Actualizar
        </button>
      </div>

      {/* Fila superior: Toggle + QR */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">

        {/* Toggle Stand */}
        <div className="glass-panel rounded-2xl p-6">
          <h2 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">Estado del stand</h2>
          <div className="flex items-center justify-between">
            <div>
              <p className={`text-lg font-black ${standEnabled ? "text-green-400" : "text-red-400"}`}>
                {standEnabled ? "🟢 Registro ACTIVO" : "🔴 Registro INACTIVO"}
              </p>
              <p className="text-gray-500 text-xs mt-1">
                {standEnabled
                  ? "La URL pública /registro acepta nuevas personas"
                  : "La URL pública /registro muestra «no disponible»"}
              </p>
            </div>
            <button
              onClick={handleToggleStand}
              disabled={togglingStand}
              title={standEnabled ? "Desactivar registro" : "Activar registro"}
              className="transition hover:opacity-80 disabled:opacity-50"
            >
              {standEnabled ? (
                <ToggleRight className="w-12 h-12 text-green-400" />
              ) : (
                <ToggleLeft className="w-12 h-12 text-gray-500" />
              )}
            </button>
          </div>
        </div>

        {/* QR */}
        <div className="glass-panel rounded-2xl p-6">
          <h2 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4 flex items-center gap-2">
            <QrCode className="w-4 h-4" /> Código QR del stand
          </h2>
          {loadingQr ? (
            <div className="flex items-center justify-center h-24 text-gray-500">
              <RefreshCw className="w-6 h-6 animate-spin" />
            </div>
          ) : qrDataUrl ? (
            <div className="flex items-center gap-4">
              <img
                src={qrDataUrl}
                alt="QR registro stand"
                className="w-24 h-24 rounded-lg border border-white/10"
              />
              <div className="flex-1 space-y-2">
                <p className="text-xs text-gray-500 break-all font-mono">{registrationUrl}</p>
                <button
                  onClick={handleDownloadQr}
                  className="flex items-center gap-1.5 text-xs text-[#0ea5c6] hover:text-[#c9a227] transition font-semibold"
                >
                  <Download className="w-3.5 h-3.5" />
                  Descargar QR
                </button>
              </div>
            </div>
          ) : (
            <p className="text-gray-500 text-sm">No se pudo cargar el QR.</p>
          )}
        </div>
      </div>

      {/* Buscador */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Buscar por número, nombre, email o teléfono…"
          className="w-full bg-[#111827] border border-[#1f2937] rounded-xl pl-10 pr-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-[#0ea5c6] transition"
        />
      </div>

      {/* Pendientes de pago */}
      <div className="glass-panel rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between">
          <h2 className="font-bold text-white flex items-center gap-2">
            <Clock className="w-4 h-4 text-yellow-400" />
            Pendientes de pago
            <span className="ml-1 bg-yellow-500/20 text-yellow-300 text-xs font-bold px-2 py-0.5 rounded-full">
              {pending.length}
            </span>
          </h2>
        </div>

        {pending.length === 0 ? (
          <div className="px-6 py-10 text-center text-gray-500">
            No hay registros pendientes{search ? " con ese criterio" : ""}.
          </div>
        ) : (
          <div className="divide-y divide-white/5">
            {pending.map((reg) => (
              <div key={reg.id} className="px-6 py-4 flex items-center justify-between gap-4">
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 rounded-xl bg-[#0ea5c6]/10 border border-[#0ea5c6]/30 flex items-center justify-center shrink-0">
                    <span className="text-[#0ea5c6] font-black text-lg">#{reg.correlativeNum}</span>
                  </div>
                  <div>
                    <p className="font-semibold text-white">{reg.name}</p>
                    <p className="text-gray-400 text-xs">{reg.phone} · {reg.email}</p>
                    <p className="text-gray-600 text-xs">{formatDate(reg.createdAt)}</p>
                  </div>
                </div>
                <button
                  onClick={() => {
                    if (reg.status === "PROCESSING") return;
                    setSelectedReg(reg);
                    setSelectedProductId("");
                    setProcessError(null);
                  }}
                  disabled={reg.status === "PROCESSING"}
                  className="shrink-0 bg-gradient-to-r from-[#7c3aed] to-[#0ea5c6] text-white font-bold text-sm px-4 py-2 rounded-xl hover:opacity-90 transition disabled:opacity-40 disabled:cursor-not-allowed"
                >
                  {reg.status === "PROCESSING" ? "Procesando…" : "Cobrar POS"}
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Historial pagados */}
      <div className="glass-panel rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-white/10">
          <h2 className="font-bold text-white flex items-center gap-2">
            <CheckCircle className="w-4 h-4 text-green-400" />
            Pagados en el evento
            <span className="ml-1 bg-green-500/20 text-green-300 text-xs font-bold px-2 py-0.5 rounded-full">
              {paid.length}
            </span>
          </h2>
        </div>

        {paid.length === 0 ? (
          <div className="px-6 py-8 text-center text-gray-500">
            Aún no hay ventas procesadas{search ? " con ese criterio" : ""}.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-gray-500 text-xs uppercase border-b border-white/5">
                  <th className="px-6 py-3 text-left font-semibold">#</th>
                  <th className="px-4 py-3 text-left font-semibold">Nombre</th>
                  <th className="px-4 py-3 text-left font-semibold">Email</th>
                  <th className="px-4 py-3 text-left font-semibold">Teléfono</th>
                  <th className="px-4 py-3 text-left font-semibold">Registrado</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {paid.map((reg) => (
                  <tr key={reg.id} className="hover:bg-white/3 transition">
                    <td className="px-6 py-3">
                      <span className="text-green-400 font-bold">#{reg.correlativeNum}</span>
                    </td>
                    <td className="px-4 py-3 text-white font-medium">{reg.name}</td>
                    <td className="px-4 py-3 text-gray-400">{reg.email}</td>
                    <td className="px-4 py-3 text-gray-400">{reg.phone}</td>
                    <td className="px-4 py-3 text-gray-500">{formatDate(reg.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Modal de cobro */}
      {selectedReg && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-[#111827] rounded-2xl border border-[#1f2937] w-full max-w-md shadow-2xl">
            <div className="px-6 py-5 border-b border-white/10">
              <h3 className="text-lg font-black text-white">Procesar pago POS</h3>
              <p className="text-gray-400 text-sm mt-1">
                Turno <span className="text-[#0ea5c6] font-bold">#{selectedReg.correlativeNum}</span> —{" "}
                {selectedReg.name}
              </p>
            </div>

            <div className="px-6 py-5 space-y-4">
              {/* Datos del cliente */}
              <div className="bg-[#0f172a] rounded-xl p-4 space-y-1 text-sm">
                <p className="text-gray-500 text-xs uppercase tracking-wider font-semibold mb-2">Datos del cliente</p>
                <p className="text-gray-300"><span className="text-gray-500">Nombre:</span> {selectedReg.name}</p>
                <p className="text-gray-300"><span className="text-gray-500">Teléfono:</span> {selectedReg.phone}</p>
                <p className="text-gray-300"><span className="text-gray-500">Email:</span> {selectedReg.email}</p>
              </div>

              {/* Selección de pack */}
              <div>
                <label className="block text-sm font-semibold text-gray-300 mb-2">
                  Selecciona el pack que compra
                </label>
                <div className="space-y-2">
                  {products.map((p) => (
                    <label
                      key={p.id}
                      className={`flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition ${
                        selectedProductId === p.id
                          ? "border-[#0ea5c6] bg-[#0ea5c6]/10"
                          : "border-white/10 bg-[#0f172a] hover:border-white/20"
                      } ${p.isLimited && p.stock < 1 ? "opacity-40 cursor-not-allowed" : ""}`}
                    >
                      <input
                        type="radio"
                        name="product"
                        value={p.id}
                        checked={selectedProductId === p.id}
                        disabled={p.isLimited && p.stock < 1}
                        onChange={() => setSelectedProductId(p.id)}
                        className="accent-[#0ea5c6]"
                      />
                      <div className="flex-1 min-w-0">
                        <p className="font-semibold text-white text-sm">{p.name}</p>
                        <p className="text-gray-500 text-xs truncate">{p.description}</p>
                      </div>
                      <div className="text-right shrink-0">
                        <p className="text-[#0ea5c6] font-bold text-sm">{formatPrice(p.price)}</p>
                        <p className="text-gray-500 text-xs">
                          {p.ticketCount} ticket{p.ticketCount !== 1 ? "s" : ""}
                        </p>
                      </div>
                    </label>
                  ))}
                </div>
              </div>

              {processError && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-3">
                  <p className="text-red-400 text-sm">{processError}</p>
                </div>
              )}

              <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-xl px-4 py-3 text-xs text-yellow-300">
                ⚠️ Asegúrate de que el cliente ya pagó en la máquina POS antes de confirmar.
              </div>
            </div>

            <div className="px-6 pb-6 flex gap-3">
              <button
                onClick={() => { setSelectedReg(null); setProcessError(null); }}
                disabled={processing}
                className="flex-1 bg-white/5 hover:bg-white/10 text-white font-semibold py-3 rounded-xl transition"
              >
                Cancelar
              </button>
              <button
                onClick={handleProcess}
                disabled={processing || !selectedProductId}
                className="flex-1 bg-gradient-to-r from-[#7c3aed] to-[#0ea5c6] text-white font-black py-3 rounded-xl hover:opacity-90 transition disabled:opacity-50"
              >
                {processing ? (
                  <span className="flex items-center justify-center gap-2">
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    Procesando…
                  </span>
                ) : (
                  "✅ Confirmar pago POS"
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
