import { useState } from "react";
import { createFileRoute, Link, Navigate } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useAuth } from "@/hooks/useAuth";
import { formatDateFr } from "@/lib/format";
import {
  fetchAllEventsAdmin,
  createEvent,
  updateEvent,
  deleteEvent,
  publishEventToSocials,
  fetchPublicationsAdmin,
  type EventRow,
  type PublicationRow,
} from "@/lib/events.functions";
import { CHANNELS, CHANNEL_LABEL, buildCaption, type Channel } from "@/lib/social";
import { SOCIAL_LINKS } from "@/lib/site";

export const Route = createFileRoute("/admin/evenements")({
  head: () => ({
    meta: [
      { title: "Gestion des événements — Le Vesper" },
      {
        name: "description",
        content: "Back-office : créer, modifier et supprimer les événements.",
      },
    ],
  }),
  component: AdminEvenements,
});

const CATEGORIES = ["Soirée", "DJ Set", "Jazz", "Dégustation", "Live", "Autre"];

const PRESET_IMAGES: { label: string; url: string }[] = [
  {
    label: "Jazz",
    url: "/__l5e/assets-v1/9318e326-a7cf-42cd-85c4-b9ec0067710d/event-jazz.jpg",
  },
  {
    label: "DJ Set",
    url: "/__l5e/assets-v1/0ea47e7d-ffc4-4c5a-89a5-461153fa9cd2/event-dj.jpg",
  },
  {
    label: "Mixologie",
    url: "/__l5e/assets-v1/79e6939f-bd46-4fde-b959-ef5776bfb99d/event-mixology.jpg",
  },
  {
    label: "Salle",
    url: "/__l5e/assets-v1/d7b3f92e-c00c-4880-822f-6dc8f323ec81/lieu-salle.jpg",
  },
];

type FormState = {
  id?: string;
  title: string;
  description: string;
  category: string;
  event_date: string;
  time_label: string;
  image_url: string;
  is_featured: boolean;
  publish_instagram: boolean;
  publish_facebook: boolean;
  publish_wyylde: boolean;
  social_caption: string;
};

const PUBLISH_KEY: Record<Channel, "publish_instagram" | "publish_facebook" | "publish_wyylde"> = {
  instagram: "publish_instagram",
  facebook: "publish_facebook",
  wyylde: "publish_wyylde",
};

const STATUS_LABEL: Record<string, string> = {
  published: "Publié",
  manual: "Kit prêt",
  error: "Erreur",
  skipped: "Ignoré",
};

const STATUS_CLASS: Record<string, string> = {
  published: "border-emerald-400/40 text-emerald-300",
  manual: "border-accent/50 text-accent",
  error: "border-primary/60 text-red-300",
  skipped: "border-white/15 text-muted-foreground",
};

const EMPTY: FormState = {
  title: "",
  description: "",
  category: "Soirée",
  event_date: "",
  time_label: "",
  image_url: "",
  is_featured: false,
  publish_instagram: true,
  publish_facebook: true,
  publish_wyylde: true,
  social_caption: "",
};

function AdminEvenements() {
  const { session, loading, signOut } = useAuth();
  const queryClient = useQueryClient();

  const fetchAdmin = useServerFn(fetchAllEventsAdmin);
  const createFn = useServerFn(createEvent);
  const updateFn = useServerFn(updateEvent);
  const deleteFn = useServerFn(deleteEvent);
  const publishFn = useServerFn(publishEventToSocials);
  const fetchPubs = useServerFn(fetchPublicationsAdmin);

  const { data: events, isLoading } = useQuery({
    queryKey: ["events", "admin"],
    queryFn: fetchAdmin,
    enabled: !!session,
  });

  const { data: publications } = useQuery({
    queryKey: ["events", "publications"],
    queryFn: fetchPubs,
    enabled: !!session,
  });

  const [form, setForm] = useState<FormState>(EMPTY);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [publishingId, setPublishingId] = useState<string | null>(null);

  function pubsFor(id: string): PublicationRow[] {
    return (publications ?? []).filter((p) => p.event_id === id);
  }

  function summarize(results: { channel: Channel; status: string; error?: string | null }[]) {
    if (results.length === 0) return "Rien à diffuser : tous les canaux cochés sont déjà publiés.";
    return results
      .map(
        (r) =>
          `${CHANNEL_LABEL[r.channel]} : ${STATUS_LABEL[r.status] ?? r.status}${r.error ? ` (${r.error})` : ""}`,
      )
      .join(" · ");
  }

  async function publishNow(ev: EventRow) {
    setError(null);
    setPublishingId(ev.id);
    try {
      const results = await publishFn({ data: { id: ev.id, force: false } });
      setNotice(`« ${ev.title} » — ${summarize(results)}`);
      await queryClient.invalidateQueries({ queryKey: ["events"] });
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setPublishingId(null);
    }
  }

  async function copyWyyldeKit(ev: EventRow) {
    const text = ev.social_caption?.trim() || buildCaption(ev);
    try {
      await navigator.clipboard.writeText(text);
      setNotice("Légende copiée. Collez-la sur la page Wyylde avec le visuel de l'événement.");
    } catch {
      setNotice(text);
    }
    window.open(SOCIAL_LINKS.wyylde, "_blank", "noopener");
  }

  if (loading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background font-mono text-xs uppercase tracking-[0.3em] text-muted-foreground">
        Chargement…
      </div>
    );
  }
  if (!session) {
    return <Navigate to="/connexion" />;
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setNotice(null);
    setSaving(true);
    const payload = {
      title: form.title,
      description: form.description || null,
      category: form.category,
      event_date: form.event_date,
      time_label: form.time_label || null,
      image_url: form.image_url || null,
      is_featured: form.is_featured,
      publish_instagram: form.publish_instagram,
      publish_facebook: form.publish_facebook,
      publish_wyylde: form.publish_wyylde,
      social_caption: form.social_caption || null,
    };
    try {
      if (form.id) {
        await updateFn({ data: { id: form.id, ...payload } });
      } else {
        const created = await createFn({ data: payload });
        setNotice(`Événement créé et diffusé — ${summarize(created.publications)}`);
      }
      await queryClient.invalidateQueries({ queryKey: ["events"] });
      setForm(EMPTY);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setSaving(false);
    }
  }

  function edit(ev: EventRow) {
    setForm({
      id: ev.id,
      title: ev.title,
      description: ev.description ?? "",
      category: ev.category,
      event_date: ev.event_date,
      time_label: ev.time_label ?? "",
      image_url: ev.image_url ?? "",
      is_featured: ev.is_featured,
      publish_instagram: ev.publish_instagram,
      publish_facebook: ev.publish_facebook,
      publish_wyylde: ev.publish_wyylde,
      social_caption: ev.social_caption ?? "",
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  return (
    <div className="min-h-screen bg-background text-foreground">
      <header className="sticky top-0 z-10 border-b border-white/5 bg-background/95 backdrop-blur">
        <div className="mx-auto flex max-w-6xl items-center justify-between px-6 py-5">
          <div>
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-accent">
              Back-office
            </span>
            <h1 className="font-display text-2xl italic">Gestion des événements</h1>
          </div>
          <div className="flex items-center gap-6 text-[10px] uppercase tracking-[0.25em]">
            <Link to="/" className="text-muted-foreground hover:text-accent">
              Voir le site
            </Link>
            <button onClick={() => signOut()} className="text-muted-foreground hover:text-primary">
              Déconnexion
            </button>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-6xl px-6 py-12">
        {notice && (
          <div
            role="status"
            className="mb-8 border border-accent/30 bg-accent/5 px-4 py-3 text-sm text-foreground/90"
          >
            {notice}
          </div>
        )}
        {error && (
          <div className="mb-8 border border-primary/30 bg-primary/5 px-4 py-3 text-sm text-primary">
            {error}
          </div>
        )}

        {/* Form */}
        <form
          onSubmit={onSubmit}
          className="mb-16 grid grid-cols-1 gap-6 border border-white/5 bg-white/[0.02] p-8 md:grid-cols-2"
        >
          <h2 className="font-display text-xl italic md:col-span-2">
            {form.id ? "Modifier l'événement" : "Nouvel événement"}
          </h2>

          <label className="block md:col-span-2">
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
              Titre
            </span>
            <input
              required
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-sm outline-none focus:border-accent"
              placeholder="Soirée Jazz — Quartet Côte d'Azur"
            />
          </label>

          <label className="block">
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
              Catégorie
            </span>
            <select
              value={form.category}
              onChange={(e) => setForm({ ...form, category: e.target.value })}
              className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-sm outline-none focus:border-accent"
            >
              {CATEGORIES.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </select>
          </label>

          <label className="block">
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
              Date
            </span>
            <input
              type="date"
              required
              value={form.event_date}
              onChange={(e) => setForm({ ...form, event_date: e.target.value })}
              className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-sm outline-none focus:border-accent"
            />
          </label>

          <label className="block">
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
              Heure (libellé)
            </span>
            <input
              value={form.time_label}
              onChange={(e) => setForm({ ...form, time_label: e.target.value })}
              className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-sm outline-none focus:border-accent"
              placeholder="21:00 — 02:00"
            />
          </label>

          <div className="block">
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
              Image
            </span>
            <div className="mt-2 flex flex-wrap gap-2">
              {PRESET_IMAGES.map((p) => (
                <button
                  type="button"
                  key={p.url}
                  onClick={() => setForm({ ...form, image_url: p.url })}
                  className={`border px-3 py-1 text-[10px] uppercase tracking-tight transition-colors ${
                    form.image_url === p.url
                      ? "border-accent bg-accent/10 text-accent"
                      : "border-white/10 text-muted-foreground hover:border-white/30"
                  }`}
                >
                  {p.label}
                </button>
              ))}
            </div>
            <input
              value={form.image_url}
              onChange={(e) => setForm({ ...form, image_url: e.target.value })}
              className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-xs outline-none focus:border-accent"
              placeholder="… ou collez une URL d'image"
            />
          </div>

          <label className="block md:col-span-2">
            <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
              Description
            </span>
            <textarea
              rows={3}
              value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
              className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-sm outline-none focus:border-accent"
              placeholder="Quelques lignes pour donner envie…"
            />
          </label>

          <label className="flex items-center gap-3 md:col-span-2">
            <input
              type="checkbox"
              checked={form.is_featured}
              onChange={(e) => setForm({ ...form, is_featured: e.target.checked })}
              className="h-4 w-4 accent-[oklch(0.62_0.22_25)]"
            />
            <span className="text-sm text-muted-foreground">
              Mettre en avant (« À ne pas manquer »)
            </span>
          </label>

          <fieldset className="space-y-4 border-t border-white/5 pt-6 md:col-span-2">
            <legend className="font-mono text-[10px] uppercase tracking-[0.3em] text-accent">
              Diffusion automatique
            </legend>
            <div className="flex flex-wrap gap-6">
              {CHANNELS.map((c) => (
                <label key={c} className="flex items-center gap-3">
                  <input
                    type="checkbox"
                    checked={form[PUBLISH_KEY[c]]}
                    onChange={(e) => setForm({ ...form, [PUBLISH_KEY[c]]: e.target.checked })}
                    className="h-4 w-4 accent-[oklch(0.62_0.22_25)]"
                  />
                  <span className="text-sm">
                    {CHANNEL_LABEL[c]}
                    <span className="ml-2 text-xs text-muted-foreground">
                      {c === "wyylde" ? "kit à copier (pas d'API)" : "publié à la création"}
                    </span>
                  </span>
                </label>
              ))}
            </div>
            <label className="block">
              <span className="font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground">
                Légende réseaux (vide = générée automatiquement)
              </span>
              <textarea
                rows={5}
                value={form.social_caption}
                onChange={(e) => setForm({ ...form, social_caption: e.target.value })}
                className="mt-2 w-full border border-white/10 bg-background px-4 py-3 text-sm outline-none focus:border-accent"
                placeholder={
                  form.title && form.event_date
                    ? buildCaption({
                        title: form.title,
                        description: form.description || null,
                        event_date: form.event_date,
                        time_label: form.time_label || null,
                      })
                    : "Renseignez titre et date pour voir la légende générée."
                }
              />
            </label>
            {form.publish_instagram && !form.image_url && (
              <p className="text-xs text-red-300">
                Instagram exige une image : choisissez-en une ci-dessus.
              </p>
            )}
            {form.id && (
              <p className="text-xs text-muted-foreground">
                Une modification ne republie pas automatiquement : utilisez « Diffuser » dans la
                liste.
              </p>
            )}
          </fieldset>

          <div className="flex gap-4 md:col-span-2">
            <button
              type="submit"
              disabled={saving}
              className="bg-primary px-8 py-3 font-mono text-[10px] uppercase tracking-[0.3em] text-white transition-colors hover:bg-primary/90 disabled:opacity-50"
            >
              {saving ? "Enregistrement…" : form.id ? "Enregistrer" : "Créer et diffuser"}
            </button>
            {form.id && (
              <button
                type="button"
                onClick={() => setForm(EMPTY)}
                className="border border-white/10 px-8 py-3 font-mono text-[10px] uppercase tracking-[0.3em] text-muted-foreground hover:text-foreground"
              >
                Annuler la modification
              </button>
            )}
          </div>
        </form>

        {/* List */}
        <h2 className="mb-6 font-display text-xl italic">Tous les événements</h2>
        {isLoading ? (
          <p className="font-mono text-xs text-muted-foreground">Chargement…</p>
        ) : (
          <div className="space-y-3">
            {(events ?? []).map((ev) => {
              const { day, monthShort, year } = formatDateFr(ev.event_date);
              return (
                <div
                  key={ev.id}
                  className="grid grid-cols-1 gap-4 border border-white/5 bg-white/[0.02] p-4 md:grid-cols-[auto_1fr_auto_auto_auto_auto] md:items-center"
                >
                  <div className="bg-primary px-3 py-1 text-center font-mono text-[10px] uppercase text-white">
                    {day} {monthShort} {year}
                  </div>
                  <div>
                    <p className="font-display text-lg italic">{ev.title}</p>
                    <p className="font-mono text-[10px] uppercase tracking-tight text-muted-foreground">
                      {ev.category}
                      {ev.time_label ? ` · ${ev.time_label}` : ""}
                      {ev.is_featured ? " · À ne pas manquer" : ""}
                    </p>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {CHANNELS.filter((c) => ev[PUBLISH_KEY[c]]).map((c) => {
                        const pub = pubsFor(ev.id).find((p) => p.channel === c);
                        const status = pub?.status ?? "pending";
                        const label = `${CHANNEL_LABEL[c]} · ${STATUS_LABEL[status] ?? "À diffuser"}`;
                        const cls = `border px-2 py-0.5 font-mono text-[10px] uppercase tracking-tight ${
                          STATUS_CLASS[status] ?? "border-white/15 text-muted-foreground"
                        }`;
                        return pub?.external_url && status === "published" ? (
                          <a
                            key={c}
                            href={pub.external_url}
                            target="_blank"
                            rel="noreferrer"
                            className={cls}
                            title="Voir la publication"
                          >
                            {label}
                          </a>
                        ) : (
                          <span key={c} className={cls} title={pub?.error ?? undefined}>
                            {label}
                          </span>
                        );
                      })}
                    </div>
                  </div>
                  <button
                    onClick={() => publishNow(ev)}
                    disabled={publishingId === ev.id}
                    className="border border-accent/40 px-4 py-2 font-mono text-[10px] uppercase tracking-[0.25em] text-accent hover:bg-accent hover:text-accent-foreground disabled:opacity-50"
                  >
                    {publishingId === ev.id ? "Diffusion…" : "Diffuser"}
                  </button>
                  {ev.publish_wyylde && (
                    <button
                      onClick={() => copyWyyldeKit(ev)}
                      className="border border-white/10 px-4 py-2 font-mono text-[10px] uppercase tracking-[0.25em] text-muted-foreground hover:text-accent"
                    >
                      Kit Wyylde
                    </button>
                  )}
                  <button
                    onClick={() => edit(ev)}
                    className="border border-white/10 px-4 py-2 font-mono text-[10px] uppercase tracking-[0.25em] text-muted-foreground hover:text-accent"
                  >
                    Modifier
                  </button>
                  <button
                    onClick={async () => {
                      if (!confirm(`Supprimer « ${ev.title} » ?`)) return;
                      try {
                        await deleteFn({ data: { id: ev.id } });
                        await queryClient.invalidateQueries({ queryKey: ["events"] });
                      } catch (err) {
                        setError(err instanceof Error ? err.message : String(err));
                      }
                    }}
                    className="border border-primary/30 px-4 py-2 font-mono text-[10px] uppercase tracking-[0.25em] text-primary hover:bg-primary hover:text-white"
                  >
                    Supprimer
                  </button>
                </div>
              );
            })}
            {(events ?? []).length === 0 && (
              <p className="font-mono text-xs text-muted-foreground">
                Aucun événement. Créez-en un ci-dessus.
              </p>
            )}
          </div>
        )}
      </main>
    </div>
  );
}
