"use client";

import { useState } from "react";
import {
  ArrowDown,
  ArrowUp,
  CheckCircle,
  ExternalLink,
  Loader2,
  Plus,
  ToggleLeft,
  ToggleRight,
  Trash2,
  Video,
  XCircle,
} from "lucide-react";
import {
  MAX_AWARENESS_VIDEOS,
  PROVIDER_LABEL,
  parseVideoEmbed,
  type AwarenessVideo,
} from "@/lib/awareness-videos";

type Config = {
  awareness_enabled: string;
  awareness_position: string;
  awareness_eyebrow: string;
  awareness_title: string;
  awareness_subtitle: string;
};

type Props = { initialConfig: Config; initialVideos: AwarenessVideo[] };

const input =
  "w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white placeholder:text-gray-600 focus:border-neon-purple focus:outline-none";

export default function AdminAwarenessClient({ initialConfig, initialVideos }: Props) {
  const [config, setConfig] = useState<Config>(initialConfig);
  const [videos, setVideos] = useState<AwarenessVideo[]>(initialVideos);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState("");

  const enabled = config.awareness_enabled === "true";
  const set = (key: keyof Config, value: string) => setConfig((c) => ({ ...c, [key]: value }));

  const updateVideo = (i: number, patch: Partial<AwarenessVideo>) =>
    setVideos((list) => list.map((v, idx) => (idx === i ? { ...v, ...patch } : v)));
  const moveVideo = (i: number, dir: -1 | 1) =>
    setVideos((list) => {
      const j = i + dir;
      if (j < 0 || j >= list.length) return list;
      const next = [...list];
      [next[i], next[j]] = [next[j], next[i]];
      return next;
    });

  const invalidCount = videos.filter((v) => v.url.trim() && !parseVideoEmbed(v.url)).length;

  const save = async (override?: Partial<Config>) => {
    setSaving(true);
    setSaved(false);
    setError("");
    const body = {
      ...config,
      ...override,
      awareness_videos: JSON.stringify(videos.filter((v) => v.url.trim())),
    };
    try {
      const res = await fetch("/api/admin/site-config", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setError(data.error || "No se pudo guardar");
        return;
      }
      if (override) setConfig((c) => ({ ...c, ...override }));
      // Los enlaces no reconocidos se descartan al guardar
      setVideos((list) => list.filter((v) => parseVideoEmbed(v.url)));
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="max-w-4xl space-y-6">
      <div>
        <h1 className="flex items-center gap-2 text-2xl font-bold">
          <Video className="h-6 w-6 text-pink-400" /> Sensibilización
        </h1>
        <p className="mt-1 text-sm text-gray-400">
          Sección de videos e historias en la portada, con botones para aportar, seguir en Instagram y
          compartir. Útil para aprovechar el tráfico antes y durante la venta.
        </p>
      </div>

      {/* Encendido */}
      <section className="flex flex-col gap-4 rounded-2xl border border-pink-400/20 bg-white/5 p-6 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h2 className="text-lg font-bold">Visible en el sitio</h2>
          <p className="text-sm text-gray-400">
            El cambio se aplica al instante. El contenido se conserva aunque la sección esté apagada.
          </p>
        </div>
        <button
          type="button"
          disabled={saving}
          onClick={() => save({ awareness_enabled: enabled ? "false" : "true" })}
          className={`flex shrink-0 items-center gap-2 rounded-xl border px-4 py-2.5 text-sm font-bold transition ${
            enabled
              ? "border-green-500/40 bg-green-500/20 text-green-400"
              : "border-red-500/40 bg-red-500/20 text-red-400"
          }`}
        >
          {enabled ? <ToggleRight className="h-5 w-5" /> : <ToggleLeft className="h-5 w-5" />}
          {enabled ? "Sección ENCENDIDA" : "Sección APAGADA"}
        </button>
      </section>

      {/* Textos y ubicación */}
      <section className="space-y-4 rounded-2xl border border-white/10 bg-white/5 p-6">
        <h2 className="text-lg font-bold">Textos y ubicación</h2>
        <div>
          <label className="mb-1 block text-xs text-gray-400">Ubicación en la portada</label>
          <select
            value={config.awareness_position}
            onChange={(e) => set("awareness_position", e.target.value)}
            className={input}
          >
            <option value="top">Arriba — justo después del premio (más visible)</option>
            <option value="after_cause">Después de «La causa»</option>
          </select>
        </div>
        <div>
          <label className="mb-1 block text-xs text-gray-400">Frase manuscrita (opcional)</label>
          <input
            value={config.awareness_eyebrow}
            maxLength={80}
            onChange={(e) => set("awareness_eyebrow", e.target.value)}
            className={input}
          />
        </div>
        <div>
          <label className="mb-1 block text-xs text-gray-400">Título</label>
          <input
            value={config.awareness_title}
            maxLength={80}
            onChange={(e) => set("awareness_title", e.target.value)}
            className={input}
          />
        </div>
        <div>
          <label className="mb-1 block text-xs text-gray-400">Bajada</label>
          <textarea
            value={config.awareness_subtitle}
            maxLength={300}
            rows={2}
            onChange={(e) => set("awareness_subtitle", e.target.value)}
            className={input}
          />
        </div>
      </section>

      {/* Videos */}
      <section className="space-y-4 rounded-2xl border border-white/10 bg-white/5 p-6">
        <div className="flex items-start justify-between gap-4">
          <div>
            <h2 className="text-lg font-bold">Videos</h2>
            <p className="text-xs text-gray-400">
              Pega el enlace de YouTube (también Shorts), Instagram (post o reel), TikTok, Facebook o Vimeo.
              El video debe ser público. Máximo {MAX_AWARENESS_VIDEOS}.
            </p>
          </div>
          <button
            type="button"
            disabled={videos.length >= MAX_AWARENESS_VIDEOS}
            onClick={() => setVideos((l) => [...l, { url: "", title: "", caption: "" }])}
            className="flex shrink-0 items-center gap-1.5 rounded-xl border border-white/20 px-3 py-2 text-sm font-semibold hover:bg-white/10 disabled:opacity-40"
          >
            <Plus className="h-4 w-4" /> Agregar video
          </button>
        </div>

        {videos.length === 0 && (
          <p className="rounded-xl border border-dashed border-white/15 p-6 text-center text-sm text-gray-500">
            Sin videos aún. La sección igual muestra el título y los botones de aporte si está encendida.
          </p>
        )}

        {videos.map((v, i) => {
          const embed = v.url.trim() ? parseVideoEmbed(v.url) : null;
          return (
            <div key={i} className="space-y-3 rounded-xl border border-white/10 bg-black/30 p-4">
              <div className="flex items-center justify-between gap-2">
                <span className="text-xs font-bold uppercase tracking-wider text-gray-400">Video {i + 1}</span>
                <div className="flex items-center gap-1">
                  <button type="button" onClick={() => moveVideo(i, -1)} disabled={i === 0} className="rounded-lg p-1.5 hover:bg-white/10 disabled:opacity-30" aria-label="Subir">
                    <ArrowUp className="h-4 w-4" />
                  </button>
                  <button type="button" onClick={() => moveVideo(i, 1)} disabled={i === videos.length - 1} className="rounded-lg p-1.5 hover:bg-white/10 disabled:opacity-30" aria-label="Bajar">
                    <ArrowDown className="h-4 w-4" />
                  </button>
                  <button type="button" onClick={() => setVideos((l) => l.filter((_, idx) => idx !== i))} className="rounded-lg p-1.5 text-red-400 hover:bg-red-500/10" aria-label="Eliminar">
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>
              <input
                value={v.url}
                placeholder="https://www.instagram.com/reel/…"
                onChange={(e) => updateVideo(i, { url: e.target.value })}
                className={input}
              />
              {v.url.trim() && (
                <p className={`flex items-center gap-1.5 text-xs ${embed ? "text-green-400" : "text-red-400"}`}>
                  {embed ? (
                    <>
                      <CheckCircle className="h-3.5 w-3.5" /> {PROVIDER_LABEL[embed.provider]}
                      {embed.vertical ? " · vertical" : ""}
                      <a href={v.url} target="_blank" rel="noopener noreferrer" className="ml-2 inline-flex items-center gap-1 text-gray-400 hover:text-white">
                        abrir <ExternalLink className="h-3 w-3" />
                      </a>
                    </>
                  ) : (
                    <>
                      <XCircle className="h-3.5 w-3.5" /> Enlace no reconocido (se descartará al guardar)
                    </>
                  )}
                </p>
              )}
              <div className="grid gap-3 sm:grid-cols-2">
                <input
                  value={v.title ?? ""}
                  maxLength={80}
                  placeholder="Título (opcional)"
                  onChange={(e) => updateVideo(i, { title: e.target.value })}
                  className={input}
                />
                <input
                  value={v.caption ?? ""}
                  maxLength={240}
                  placeholder="Descripción breve (opcional)"
                  onChange={(e) => updateVideo(i, { caption: e.target.value })}
                  className={input}
                />
              </div>
            </div>
          );
        })}
      </section>

      <div className="flex items-center justify-end gap-3">
        {invalidCount > 0 && <span className="text-sm text-red-400">{invalidCount} enlace(s) no reconocido(s)</span>}
        {error && <span className="text-sm text-red-400">{error}</span>}
        {saved && (
          <span className="flex items-center gap-1 text-sm text-green-400">
            <CheckCircle className="h-4 w-4" /> Guardado
          </span>
        )}
        <a href="/#historias" target="_blank" className="rounded-xl border border-white/20 px-4 py-2.5 text-sm font-semibold hover:bg-white/10">
          Ver en el sitio
        </a>
        <button
          type="button"
          onClick={() => save()}
          disabled={saving}
          className="flex items-center gap-2 rounded-xl bg-gradient-to-r from-neon-blue to-neon-purple px-5 py-2.5 font-semibold text-white hover:opacity-90 disabled:opacity-50"
        >
          {saving && <Loader2 className="h-4 w-4 animate-spin" />}
          Guardar cambios
        </button>
      </div>
    </div>
  );
}
