"use client";

import { useMemo, useState } from "react";
import { Pencil, Trash2, Plus, Loader2, Ticket, ShoppingBag, Eye, EyeOff } from "lucide-react";
import ImageUploader from "@/components/ImageUploader";
import { normalizeMediaUrl } from "@/lib/media-url";

type Product = {
  id: string;
  name: string;
  description: string;
  price: number;
  ticketCount: number;
  stock: number;
  image: string | null;
  type?: string;
  category?: string | null;
  isLimited?: boolean;
};

export type ProductCatalog = "TICKET" | "PHYSICAL";

const CATALOG_CONFIG = {
  TICKET: {
    title: "Láminas / Tickets",
    subtitle: "Packs que entregan números para el sorteo",
    icon: Ticket,
    addLabel: "Nueva lámina",
    emptyLabel: "No hay láminas. Crea la primera.",
    modalNew: "Nueva lámina",
    modalEdit: "Editar lámina",
    imageLabel: "Imagen de la lámina",
    namePlaceholder: "Ej: Pack 4 láminas",
    stockDefault: 9999,
    stockRestore: 9999,
  },
  PHYSICAL: {
    title: "Tienda / Merchandising",
    subtitle: "Productos físicos (ropa, accesorios) con envío — no generan números de sorteo",
    icon: ShoppingBag,
    addLabel: "Nuevo producto",
    emptyLabel: "No hay productos en la tienda. Crea el primero.",
    modalNew: "Nuevo producto físico",
    modalEdit: "Editar producto",
    imageLabel: "Imagen del producto",
    namePlaceholder: "Ej: Polera Creciendo con Amor",
    stockDefault: 50,
    stockRestore: 25,
  },
} as const;

function emptyProduct(catalog: ProductCatalog): Omit<Product, "id"> {
  const cfg = CATALOG_CONFIG[catalog];
  return {
    name: "",
    description: "",
    price: catalog === "TICKET" ? 10000 : 15990,
    ticketCount: catalog === "TICKET" ? 1 : 0,
    stock: cfg.stockDefault,
    image: "",
    type: catalog,
    category: catalog === "PHYSICAL" ? "" : null,
    isLimited: false,
  };
}

type Props = {
  catalog: ProductCatalog;
  initialProducts: Product[];
};

export default function AdminProductsClient({ catalog, initialProducts }: Props) {
  const cfg = CATALOG_CONFIG[catalog];
  const Icon = cfg.icon;

  const catalogProducts = useMemo(
    () =>
      initialProducts.filter((p) =>
        catalog === "PHYSICAL" ? p.type === "PHYSICAL" : p.type !== "PHYSICAL"
      ),
    [initialProducts, catalog]
  );

  const [products, setProducts] = useState<Product[]>(catalogProducts);
  const [editing, setEditing] = useState<(Partial<Product> & { isNew?: boolean }) | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const openNew = () => setEditing({ ...emptyProduct(catalog), isNew: true });
  const openEdit = (p: Product) => setEditing({ ...p, isNew: false });
  const closeModal = () => {
    setEditing(null);
    setError("");
  };

  const save = async () => {
    if (!editing) return;
    setLoading(true);
    setError("");
    try {
      const isNew = editing.isNew;
      const url = isNew ? "/api/admin/products" : `/api/admin/products/${editing.id}`;
      const method = isNew ? "POST" : "PUT";
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: editing.name,
          description: editing.description,
          price: Number(editing.price),
          ticketCount: catalog === "PHYSICAL" ? 0 : Number(editing.ticketCount),
          stock: Number(editing.stock),
          image: editing.image || null,
          type: catalog,
          category: catalog === "PHYSICAL" ? editing.category || null : null,
          isLimited: Boolean(editing.isLimited),
        }),
      });

      const rawText = await res.text();
      let data: { product?: Product; error?: string } = {};
      try {
        data = rawText ? JSON.parse(rawText) : {};
      } catch {
        setError(
          res.ok
            ? "Respuesta inesperada del servidor."
            : `Error ${res.status}: el servidor devolvió una respuesta no válida. Revisa la consola del dev server.`
        );
        return;
      }

      if (!res.ok) {
        setError(data.error || `Error ${res.status} al guardar`);
        return;
      }
      if (!data.product) {
        setError("Respuesta sin producto");
        return;
      }
      if (isNew) {
        setProducts((prev) => [...prev, data.product!]);
      } else {
        setProducts((prev) => prev.map((p) => (p.id === data.product!.id ? data.product! : p)));
      }
      closeModal();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Error de red al guardar");
    } finally {
      setLoading(false);
    }
  };

  const toggleStock = async (product: Product) => {
    const newStock = product.stock > 0 ? 0 : cfg.stockRestore;
    setProducts((prev) => prev.map((p) => (p.id === product.id ? { ...p, stock: newStock } : p)));
    await fetch(`/api/admin/products/${product.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ stock: newStock }),
    });
  };

  const deleteProduct = async (id: string) => {
    const label = catalog === "TICKET" ? "lámina" : "producto";
    if (!confirm(`¿Eliminar este ${label}? Si tiene ventas asociadas, se ocultará.`)) return;
    const res = await fetch(`/api/admin/products/${id}`, { method: "DELETE" });
    const data = await res.json();
    if (data.hidden) {
      setProducts((prev) => prev.map((p) => (p.id === id ? { ...p, stock: 0 } : p)));
    } else if (data.ok) {
      setProducts((prev) => prev.filter((p) => p.id !== id));
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <Icon className="text-neon-purple w-7 h-7" />
            <h1 className="text-3xl font-bold">{cfg.title}</h1>
          </div>
          <p className="text-gray-400 text-sm mt-2 max-w-xl">{cfg.subtitle}</p>
        </div>
        <button
          onClick={openNew}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-gradient-to-r from-neon-blue to-neon-purple rounded-xl text-white font-semibold hover:opacity-90 transition-opacity shrink-0"
        >
          <Plus className="w-4 h-4" /> {cfg.addLabel}
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        {products.map((p) => {
          const imgSrc = normalizeMediaUrl(p.image);
          return (
            <div
              key={p.id}
              className={`rounded-xl border bg-white/5 overflow-hidden transition-all ${
                p.stock > 0 ? "border-white/10" : "border-white/5 opacity-50"
              }`}
            >
              <div className="h-44 relative overflow-hidden bg-black/30">
                {imgSrc ? (
                  <img
                    src={imgSrc}
                    alt={p.name}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = "/logo-fundacion.png";
                    }}
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-gray-600">
                    <Icon className="w-12 h-12" />
                  </div>
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent" />
                <div className="absolute bottom-3 left-3 right-3 flex items-end justify-between gap-2">
                  <span className="text-white font-bold drop-shadow">{p.name}</span>
                  {p.stock > 0 ? (
                    catalog === "TICKET" && p.isLimited ? (
                      <span className="text-xs px-2 py-0.5 rounded-full font-bold whitespace-nowrap bg-[#0ea5c6]/90 text-black">
                        Limitada · {p.stock}
                      </span>
                    ) : (
                      <span className="text-xs px-2 py-0.5 rounded-full font-bold whitespace-nowrap bg-green-500/80 text-white">
                        Visible
                      </span>
                    )
                  ) : (
                    <span className="text-xs px-2 py-0.5 rounded-full font-bold whitespace-nowrap bg-red-500/80 text-white">
                      {catalog === "PHYSICAL" ? "Sin stock" : "Oculto"}
                    </span>
                  )}
                </div>
              </div>
              <div className="p-4 space-y-2">
                {catalog === "PHYSICAL" && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Categoría</span>
                    <span className="font-semibold text-[#0ea5c6]">{p.category || "General"}</span>
                  </div>
                )}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-400">Precio</span>
                  <span className="font-bold text-neon-blue">${p.price.toLocaleString("es-CL")}</span>
                </div>
                {catalog === "TICKET" && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Tickets que entrega</span>
                    <span className="font-bold text-neon-purple">{p.ticketCount}</span>
                  </div>
                )}
                {catalog === "PHYSICAL" && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">Stock</span>
                    <span className="font-bold text-white">{p.stock}</span>
                  </div>
                )}
                <p className="text-xs text-gray-500 line-clamp-2">{p.description}</p>
                <div className="flex items-center gap-2 pt-2">
                  <button
                    onClick={() => openEdit(p)}
                    className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-sm transition-colors"
                  >
                    <Pencil className="w-3.5 h-3.5" /> Editar
                  </button>
                  <button
                    onClick={() => toggleStock(p)}
                    className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-sm transition-colors"
                  >
                    {p.stock > 0 ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
                    {p.stock > 0 ? "Ocultar" : "Mostrar"}
                  </button>
                  <button
                    onClick={() => deleteProduct(p.id)}
                    className="ml-auto flex items-center gap-1 px-3 py-1.5 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 text-sm transition-colors"
                  >
                    <Trash2 className="w-3.5 h-3.5" /> Eliminar
                  </button>
                </div>
              </div>
            </div>
          );
        })}
        {products.length === 0 && (
          <div className="col-span-full text-center text-gray-500 py-16 border border-dashed border-white/10 rounded-xl">
            {cfg.emptyLabel}
          </div>
        )}
      </div>

      {editing && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-[#111] border border-white/10 rounded-2xl w-full max-w-lg max-h-[92vh] overflow-y-auto">
            <div className="p-6 border-b border-white/10 flex items-center justify-between">
              <h2 className="text-xl font-bold">{editing.isNew ? cfg.modalNew : cfg.modalEdit}</h2>
              <button onClick={closeModal} className="text-gray-400 hover:text-white text-xl">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {error && (
                <p className="text-red-400 text-sm bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2">
                  {error}
                </p>
              )}

              <div>
                <label className="block text-xs text-gray-400 mb-1">Nombre *</label>
                <input
                  className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-neon-blue"
                  value={editing.name || ""}
                  onChange={(e) => setEditing((prev) => ({ ...prev!, name: e.target.value }))}
                  placeholder={cfg.namePlaceholder}
                />
              </div>

              {catalog === "PHYSICAL" && (
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Categoría *</label>
                  <input
                    className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-neon-blue"
                    value={editing.category || ""}
                    onChange={(e) => setEditing((prev) => ({ ...prev!, category: e.target.value }))}
                    placeholder="Ej: Ropa, Merchandising, Gorros..."
                  />
                </div>
              )}

              <div>
                <label className="block text-xs text-gray-400 mb-1">Descripción</label>
                <textarea
                  rows={2}
                  className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-neon-blue resize-none"
                  value={editing.description || ""}
                  onChange={(e) =>
                    setEditing((prev) => ({ ...prev!, description: e.target.value }))
                  }
                  placeholder="Descripción breve..."
                />
              </div>

              {catalog === "TICKET" && (
                <label className="flex items-start gap-3 cursor-pointer rounded-xl border border-[#0ea5c6]/30 bg-[#0ea5c6]/5 hover:bg-[#0ea5c6]/10 p-4 transition-colors">
                  <input
                    type="checkbox"
                    checked={Boolean(editing.isLimited)}
                    onChange={(e) =>
                      setEditing((prev) => ({ ...prev!, isLimited: e.target.checked }))
                    }
                    className="w-5 h-5 mt-0.5 accent-[#0ea5c6] cursor-pointer"
                  />
                  <div className="flex-1">
                    <div className="text-sm font-semibold text-white">
                      Lámina con cantidad limitada
                    </div>
                    <div className="text-xs text-gray-400 mt-0.5">
                      Si lo activas, en la portada aparece{" "}
                      <span className="text-[#0ea5c6] font-semibold">“Quedan X disponibles”</span> y
                      el carrito impide comprar más unidades que el stock real.
                    </div>
                  </div>
                </label>
              )}

              <div className={`grid gap-3 ${catalog === "TICKET" ? "grid-cols-3" : "grid-cols-2"}`}>
                <div>
                  <label className="block text-xs text-gray-400 mb-1">Precio ($) *</label>
                  <input
                    type="number"
                    min={1}
                    className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-3 text-white focus:outline-none focus:border-neon-blue"
                    value={editing.price ?? (catalog === "TICKET" ? 10000 : 15990)}
                    onChange={(e) =>
                      setEditing((prev) => ({ ...prev!, price: Number(e.target.value) }))
                    }
                  />
                </div>
                {catalog === "TICKET" && (
                  <div>
                    <label className="block text-xs text-gray-400 mb-1">Nº tickets *</label>
                    <input
                      type="number"
                      min={1}
                      className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-3 text-white focus:outline-none focus:border-neon-blue"
                      value={editing.ticketCount ?? 1}
                      onChange={(e) =>
                        setEditing((prev) => ({
                          ...prev!,
                          ticketCount: Number(e.target.value),
                        }))
                      }
                    />
                  </div>
                )}
                <div>
                  <label className="block text-xs text-gray-400 mb-1">
                    {catalog === "PHYSICAL" || editing.isLimited ? "Stock *" : "Stock (0 = oculto)"}
                  </label>
                  <input
                    type="number"
                    min={0}
                    className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-3 text-white focus:outline-none focus:border-neon-blue"
                    value={editing.stock ?? cfg.stockDefault}
                    onChange={(e) =>
                      setEditing((prev) => ({ ...prev!, stock: Number(e.target.value) }))
                    }
                  />
                </div>
              </div>

              <ImageUploader
                label={cfg.imageLabel}
                value={editing.image || ""}
                onChange={(url) => setEditing((prev) => ({ ...prev!, image: url }))}
              />
            </div>

            <div className="p-6 border-t border-white/10 flex gap-3 justify-end">
              <button
                onClick={closeModal}
                className="px-4 py-2 rounded-xl border border-white/10 text-gray-400 hover:text-white transition-colors"
              >
                Cancelar
              </button>
              <button
                onClick={save}
                disabled={loading || (catalog === "PHYSICAL" && !editing.category?.trim())}
                className="px-6 py-2 rounded-xl bg-gradient-to-r from-neon-blue to-neon-purple text-white font-semibold hover:opacity-90 disabled:opacity-50 flex items-center gap-2"
              >
                {loading && <Loader2 className="w-4 h-4 animate-spin" />}
                {editing.isNew ? "Crear" : "Guardar"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
