"use client";

import Image from "next/image";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import type { TruckEvent, TruckEventRecurrence } from "@/generated/prisma/client";
import { ADMIN_API } from "@/lib/constants";
import { isUploadAssetPath } from "@/lib/image-url";
import { WEEKDAY_LABELS } from "@/lib/truck-schedule-shared";
import { formatDateIso } from "@/lib/week-calendar";

type EventMode = "once" | "recurring";

type OnceForm = {
  eventDate: string;
  timeLabel: string;
  location: string;
  note: string;
  imageUrl: string;
};

type RecurForm = {
  dayOfWeek: string;
  timeLabel: string;
  location: string;
  note: string;
  imageUrl: string;
};

const emptyOnceForm = (): OnceForm => ({
  eventDate: "",
  timeLabel: "",
  location: "",
  note: "",
  imageUrl: "",
});

const emptyRecurForm = (): RecurForm => ({
  dayOfWeek: "0",
  timeLabel: "",
  location: "",
  note: "",
  imageUrl: "",
});

export function AdminTruckSchedule() {
  const router = useRouter();
  const [events, setEvents] = useState<TruckEvent[]>([]);
  const [recurrences, setRecurrences] = useState<TruckEventRecurrence[]>([]);
  const [scheduleIntro, setScheduleIntro] = useState("");
  const [loading, setLoading] = useState(true);
  const [eventMode, setEventMode] = useState<EventMode>("once");
  const [saving, setSaving] = useState(false);
  const [savingIntro, setSavingIntro] = useState(false);
  const [uploadingOnceImage, setUploadingOnceImage] = useState(false);
  const [uploadingRecurImage, setUploadingRecurImage] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingRecurId, setEditingRecurId] = useState<string | null>(null);
  const [onceForm, setOnceForm] = useState<OnceForm>(emptyOnceForm);
  const [recurForm, setRecurForm] = useState<RecurForm>(emptyRecurForm);

  const { upcomingEvents, pastEvents } = useMemo(() => {
    const today = formatDateIso(new Date());
    const upcoming: TruckEvent[] = [];
    const past: TruckEvent[] = [];
    for (const ev of events) {
      if (ev.eventDate < today) past.push(ev);
      else upcoming.push(ev);
    }
    past.sort((a, b) => b.eventDate.localeCompare(a.eventDate));
    return { upcomingEvents: upcoming, pastEvents: past };
  }, [events]);

  const load = useCallback(async () => {
    const [eventsRes, recurRes, siteRes] = await Promise.all([
      fetch(`${ADMIN_API}/truck-events`, { credentials: "include" }),
      fetch(`${ADMIN_API}/truck-recurrences`, { credentials: "include" }),
      fetch(`${ADMIN_API}/site-content`, { credentials: "include" }),
    ]);
    if (
      eventsRes.status === 401 ||
      recurRes.status === 401 ||
      siteRes.status === 401
    ) {
      router.replace("/admin/login");
      return;
    }
    const eventsData = await eventsRes.json().catch(() => []);
    const recurData = await recurRes.json().catch(() => []);
    const siteData = await siteRes.json().catch(() => ({}));
    setEvents(Array.isArray(eventsData) ? eventsData : []);
    setRecurrences(Array.isArray(recurData) ? recurData : []);
    setScheduleIntro(String(siteData.scheduleIntro ?? ""));
    setLoading(false);
  }, [router]);

  useEffect(() => {
    load();
  }, [load]);

  function resetOnceForm() {
    setEditingId(null);
    setOnceForm(emptyOnceForm());
  }

  function resetRecurForm() {
    setEditingRecurId(null);
    setRecurForm(emptyRecurForm());
  }

  function startEditOnce(ev: TruckEvent) {
    setEventMode("once");
    setEditingId(ev.id);
    resetRecurForm();
    setOnceForm({
      eventDate: ev.eventDate,
      timeLabel: ev.timeLabel,
      location: ev.location,
      note: ev.note,
      imageUrl: ev.imageUrl ?? "",
    });
  }

  function startEditRecur(r: TruckEventRecurrence) {
    setEventMode("recurring");
    setEditingRecurId(r.id);
    resetOnceForm();
    setRecurForm({
      dayOfWeek: String(r.dayOfWeek),
      timeLabel: r.timeLabel,
      location: r.location,
      note: r.note,
      imageUrl: r.imageUrl ?? "",
    });
  }

  async function uploadImage(
    e: React.ChangeEvent<HTMLInputElement>,
    onUrl: (url: string) => void,
    setUploading: (v: boolean) => void
  ) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch(`${ADMIN_API}/upload`, {
        method: "POST",
        body: fd,
        credentials: "include",
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        alert(typeof data.error === "string" ? data.error : "Échec de l’envoi");
        return;
      }
      if (data.url) onUrl(data.url);
    } finally {
      setUploading(false);
      e.target.value = "";
    }
  }

  async function onSubmitOnce(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const url = editingId
        ? `${ADMIN_API}/truck-events/${editingId}`
        : `${ADMIN_API}/truck-events`;
      const res = await fetch(url, {
        method: editingId ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify(onceForm),
      });
      if (res.status === 401) {
        router.replace("/admin/login");
        return;
      }
      const err = await res.json().catch(() => ({}));
      if (!res.ok) {
        alert(typeof err.error === "string" ? err.error : "Erreur");
        return;
      }
      resetOnceForm();
      await load();
    } finally {
      setSaving(false);
    }
  }

  async function onSubmitRecur(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const url = editingRecurId
        ? `${ADMIN_API}/truck-recurrences/${editingRecurId}`
        : `${ADMIN_API}/truck-recurrences`;
      const res = await fetch(url, {
        method: editingRecurId ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          ...recurForm,
          dayOfWeek: Number(recurForm.dayOfWeek),
          active: true,
        }),
      });
      if (res.status === 401) {
        router.replace("/admin/login");
        return;
      }
      const err = await res.json().catch(() => ({}));
      if (!res.ok) {
        alert(typeof err.error === "string" ? err.error : "Erreur");
        return;
      }
      resetRecurForm();
      await load();
    } finally {
      setSaving(false);
    }
  }

  async function removeOnce(id: string) {
    if (!confirm("Supprimer cet événement ponctuel ?")) return;
    const res = await fetch(`${ADMIN_API}/truck-events/${id}`, {
      method: "DELETE",
      credentials: "include",
    });
    if (!res.ok) {
      alert("Suppression impossible");
      return;
    }
    if (editingId === id) resetOnceForm();
    await load();
  }

  async function removeRecur(id: string) {
    if (!confirm("Supprimer cette récurrence ?")) return;
    const res = await fetch(`${ADMIN_API}/truck-recurrences/${id}`, {
      method: "DELETE",
      credentials: "include",
    });
    if (!res.ok) {
      alert("Suppression impossible");
      return;
    }
    if (editingRecurId === id) resetRecurForm();
    await load();
  }

  async function toggleRecurActive(r: TruckEventRecurrence) {
    const res = await fetch(`${ADMIN_API}/truck-recurrences/${r.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({
        dayOfWeek: r.dayOfWeek,
        timeLabel: r.timeLabel,
        location: r.location,
        note: r.note,
        imageUrl: r.imageUrl ?? "",
        active: !r.active,
      }),
    });
    if (!res.ok) {
      alert("Mise à jour impossible");
      return;
    }
    await load();
  }

  async function saveIntro() {
    setSavingIntro(true);
    try {
      const siteRes = await fetch(`${ADMIN_API}/site-content`, {
        credentials: "include",
      });
      if (siteRes.status === 401) {
        router.replace("/admin/login");
        return;
      }
      const site = await siteRes.json();
      const res = await fetch(`${ADMIN_API}/site-content`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ ...site, scheduleIntro }),
      });
      if (!res.ok) {
        alert("Erreur lors de l’enregistrement du texte");
      }
    } finally {
      setSavingIntro(false);
    }
  }

  async function logout() {
    const res = await fetch(`${ADMIN_API}/auth/logout`, {
      method: "POST",
      credentials: "include",
    });
    if (res.ok) {
      window.location.href = "/admin/login";
      return;
    }
    router.replace("/admin/login");
  }

  return (
    <div className="px-4 py-10 sm:px-6">
      <div className="mx-auto max-w-4xl">
        <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-bold text-chocolat">Où me trouver</h1>
            <p className="text-sm text-muted">
              Calendrier hebdomadaire des présences du food truck.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <a
              href="/#ou-me-trouver"
              target="_blank"
              rel="noopener noreferrer"
              className="rounded-full border border-chocolat/20 px-4 py-2 text-sm font-medium text-chocolat hover:bg-white"
            >
              Voir sur le site
            </a>
            <button
              type="button"
              onClick={() => logout()}
              className="rounded-full bg-chocolat px-4 py-2 text-sm font-medium text-cream hover:opacity-90"
            >
              Déconnexion
            </button>
          </div>
        </div>

        {loading ? (
          <p className="text-muted">Chargement…</p>
        ) : (
          <div className="space-y-8">
            <section className="rounded-[2rem] border border-chocolat/10 bg-white p-6 shadow-[0_12px_40px_-12px_rgba(61,43,31,0.12)]">
              <h2 className="text-lg font-semibold text-chocolat">
                Texte de la section
              </h2>
              <label className="mt-4 flex flex-col gap-1 text-sm font-medium text-chocolat">
                Introduction sous le titre « Où me trouver »
                <textarea
                  value={scheduleIntro}
                  onChange={(e) => setScheduleIntro(e.target.value)}
                  rows={2}
                  placeholder="Ex. Retrouvez-nous sur les marchés de la semaine…"
                  className="resize-y rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                />
              </label>
              <button
                type="button"
                onClick={() => saveIntro()}
                disabled={savingIntro}
                className="mt-4 rounded-full bg-gaufre px-5 py-2 text-sm font-semibold text-chocolat disabled:opacity-60"
              >
                {savingIntro ? "Enregistrement…" : "Enregistrer le texte"}
              </button>
            </section>

            <section className="rounded-[2rem] border border-chocolat/10 bg-white p-6 shadow-[0_12px_40px_-12px_rgba(61,43,31,0.12)]">
              <h2 className="text-lg font-semibold text-chocolat">
                Ajouter une présence
              </h2>
              <div className="mt-4 flex flex-wrap gap-2">
                <button
                  type="button"
                  onClick={() => {
                    setEventMode("once");
                    resetRecurForm();
                  }}
                  className={`rounded-full px-4 py-2 text-sm font-medium transition ${
                    eventMode === "once"
                      ? "bg-gaufre text-chocolat"
                      : "border border-chocolat/20 text-chocolat hover:bg-cream"
                  }`}
                >
                  Événement ponctuel
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setEventMode("recurring");
                    resetOnceForm();
                  }}
                  className={`rounded-full px-4 py-2 text-sm font-medium transition ${
                    eventMode === "recurring"
                      ? "bg-gaufre text-chocolat"
                      : "border border-chocolat/20 text-chocolat hover:bg-cream"
                  }`}
                >
                  Événement récurrent
                </button>
              </div>
              <p className="mt-2 text-xs text-muted">
                {eventMode === "once"
                  ? "Une date précise (marché exceptionnel, festival…)."
                  : "Répété chaque semaine le même jour (ex. tous les mardis)."}
              </p>

              {eventMode === "once" ? (
                <form
                  onSubmit={onSubmitOnce}
                  className="mt-4 grid gap-4 sm:grid-cols-2"
                >
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat">
                    Date
                    <input
                      type="date"
                      required
                      value={onceForm.eventDate}
                      onChange={(e) =>
                        setOnceForm((f) => ({ ...f, eventDate: e.target.value }))
                      }
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat">
                    Horaires (optionnel)
                    <input
                      value={onceForm.timeLabel}
                      onChange={(e) =>
                        setOnceForm((f) => ({ ...f, timeLabel: e.target.value }))
                      }
                      placeholder="11h — 18h"
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat sm:col-span-2">
                    Lieu / événement
                    <input
                      required
                      value={onceForm.location}
                      onChange={(e) =>
                        setOnceForm((f) => ({ ...f, location: e.target.value }))
                      }
                      placeholder="Marché de Bagnols-sur-Cèze"
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat sm:col-span-2">
                    Note (optionnel)
                    <input
                      value={onceForm.note}
                      onChange={(e) =>
                        setOnceForm((f) => ({ ...f, note: e.target.value }))
                      }
                      placeholder="Place du marché, stand n°3…"
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <EventImageField
                    imageUrl={onceForm.imageUrl}
                    uploading={uploadingOnceImage}
                    onUpload={(e) =>
                      uploadImage(
                        e,
                        (url) => setOnceForm((f) => ({ ...f, imageUrl: url })),
                        setUploadingOnceImage
                      )
                    }
                    onUrlChange={(imageUrl) =>
                      setOnceForm((f) => ({ ...f, imageUrl }))
                    }
                    onClear={() => setOnceForm((f) => ({ ...f, imageUrl: "" }))}
                  />
                  <div className="flex flex-wrap gap-2 sm:col-span-2">
                    <button
                      type="submit"
                      disabled={saving}
                      className="rounded-full bg-gaufre px-6 py-2.5 text-sm font-semibold text-chocolat disabled:opacity-60"
                    >
                      {saving
                        ? "Enregistrement…"
                        : editingId
                          ? "Mettre à jour"
                          : "Ajouter"}
                    </button>
                    {editingId ? (
                      <button
                        type="button"
                        onClick={() => resetOnceForm()}
                        className="rounded-full border border-chocolat/20 px-4 py-2.5 text-sm font-medium text-chocolat"
                      >
                        Annuler
                      </button>
                    ) : null}
                  </div>
                </form>
              ) : (
                <form
                  onSubmit={onSubmitRecur}
                  className="mt-4 grid gap-4 sm:grid-cols-2"
                >
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat">
                    Jour de la semaine
                    <select
                      required
                      value={recurForm.dayOfWeek}
                      onChange={(e) =>
                        setRecurForm((f) => ({ ...f, dayOfWeek: e.target.value }))
                      }
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    >
                      {WEEKDAY_LABELS.map((label, i) => (
                        <option key={label} value={String(i)}>
                          {label}
                        </option>
                      ))}
                    </select>
                  </label>
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat">
                    Horaires (optionnel)
                    <input
                      value={recurForm.timeLabel}
                      onChange={(e) =>
                        setRecurForm((f) => ({ ...f, timeLabel: e.target.value }))
                      }
                      placeholder="9h — 13h"
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat sm:col-span-2">
                    Lieu / événement
                    <input
                      required
                      value={recurForm.location}
                      onChange={(e) =>
                        setRecurForm((f) => ({ ...f, location: e.target.value }))
                      }
                      placeholder="Marché de Bagnols-sur-Cèze"
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <label className="flex flex-col gap-1 text-sm font-medium text-chocolat sm:col-span-2">
                    Note (optionnel)
                    <input
                      value={recurForm.note}
                      onChange={(e) =>
                        setRecurForm((f) => ({ ...f, note: e.target.value }))
                      }
                      className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
                    />
                  </label>
                  <EventImageField
                    imageUrl={recurForm.imageUrl}
                    uploading={uploadingRecurImage}
                    onUpload={(e) =>
                      uploadImage(
                        e,
                        (url) => setRecurForm((f) => ({ ...f, imageUrl: url })),
                        setUploadingRecurImage
                      )
                    }
                    onUrlChange={(imageUrl) =>
                      setRecurForm((f) => ({ ...f, imageUrl }))
                    }
                    onClear={() => setRecurForm((f) => ({ ...f, imageUrl: "" }))}
                  />
                  <div className="flex flex-wrap gap-2 sm:col-span-2">
                    <button
                      type="submit"
                      disabled={saving}
                      className="rounded-full bg-gaufre px-6 py-2.5 text-sm font-semibold text-chocolat disabled:opacity-60"
                    >
                      {saving
                        ? "Enregistrement…"
                        : editingRecurId
                          ? "Mettre à jour"
                          : "Enregistrer la récurrence"}
                    </button>
                    {editingRecurId ? (
                      <button
                        type="button"
                        onClick={() => resetRecurForm()}
                        className="rounded-full border border-chocolat/20 px-4 py-2.5 text-sm font-medium text-chocolat"
                      >
                        Annuler
                      </button>
                    ) : null}
                  </div>
                </form>
              )}
            </section>

            <section className="rounded-[2rem] border border-chocolat/10 bg-white p-6 shadow-[0_12px_40px_-12px_rgba(61,43,31,0.12)]">
              <h2 className="text-lg font-semibold text-chocolat">
                Événements récurrents
              </h2>
              <p className="mt-1 text-xs text-muted">
                Affichés automatiquement chaque semaine sur le calendrier public.
              </p>
              {recurrences.length === 0 ? (
                <p className="mt-4 text-sm text-muted">Aucune récurrence.</p>
              ) : (
                <ul className="mt-4 space-y-3">
                  {recurrences.map((r) => (
                    <li
                      key={r.id}
                      className={`flex flex-col gap-3 rounded-2xl border p-4 sm:flex-row sm:items-center sm:justify-between ${
                        r.active
                          ? "border-chocolat/10 bg-cream/30"
                          : "border-dashed border-chocolat/20 bg-cream/10 opacity-70"
                      }`}
                    >
                      <div className="flex min-w-0 gap-3">
                        {r.imageUrl ? (
                          <EventListThumb src={r.imageUrl} alt={r.location} />
                        ) : null}
                        <div className="min-w-0">
                          <p className="text-sm font-semibold text-chocolat">
                            Chaque {WEEKDAY_LABELS[r.dayOfWeek]}
                            {r.timeLabel ? ` · ${r.timeLabel}` : ""}
                            {!r.active ? " (désactivé)" : ""}
                          </p>
                          <p className="font-medium text-chocolat">{r.location}</p>
                          {r.note ? (
                            <p className="text-sm text-muted">{r.note}</p>
                          ) : null}
                        </div>
                      </div>
                      <div className="flex shrink-0 flex-wrap gap-2">
                        <button
                          type="button"
                          onClick={() => toggleRecurActive(r)}
                          className="rounded-full border border-chocolat/20 px-4 py-2 text-sm font-medium text-chocolat hover:bg-white"
                        >
                          {r.active ? "Désactiver" : "Activer"}
                        </button>
                        <button
                          type="button"
                          onClick={() => startEditRecur(r)}
                          className="rounded-full border border-chocolat/20 px-4 py-2 text-sm font-medium text-chocolat hover:bg-white"
                        >
                          Modifier
                        </button>
                        <button
                          type="button"
                          onClick={() => removeRecur(r.id)}
                          className="rounded-full border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-800"
                        >
                          Supprimer
                        </button>
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </section>

            <section className="rounded-[2rem] border border-chocolat/10 bg-white p-6 shadow-[0_12px_40px_-12px_rgba(61,43,31,0.12)]">
              <h2 className="text-lg font-semibold text-chocolat">
                Événements ponctuels
              </h2>
              <p className="mt-1 text-xs text-muted">
                Événements à venir (aujourd’hui et après).
              </p>
              {upcomingEvents.length === 0 ? (
                <p className="mt-4 text-sm text-muted">
                  Aucun événement ponctuel à venir.
                </p>
              ) : (
                <OnceEventList
                  items={upcomingEvents}
                  onEdit={startEditOnce}
                  onRemove={removeOnce}
                />
              )}
            </section>

            {pastEvents.length > 0 ? (
              <section className="rounded-[2rem] border border-chocolat/10 bg-white p-6 shadow-[0_12px_40px_-12px_rgba(61,43,31,0.12)]">
                <h2 className="text-lg font-semibold text-chocolat">
                  Événements Historique
                </h2>
                <p className="mt-1 text-xs text-muted">
                  Événements ponctuels déjà passés.
                </p>
                <OnceEventList
                  items={pastEvents}
                  muted
                  onEdit={startEditOnce}
                  onRemove={removeOnce}
                />
              </section>
            ) : null}
          </div>
        )}
      </div>
    </div>
  );
}

function OnceEventList({
  items,
  muted,
  onEdit,
  onRemove,
}: {
  items: TruckEvent[];
  muted?: boolean;
  onEdit: (ev: TruckEvent) => void;
  onRemove: (id: string) => void;
}) {
  return (
    <ul className="mt-4 space-y-3">
      {items.map((ev) => (
        <li
          key={ev.id}
          className={`flex flex-col gap-3 rounded-2xl border p-4 sm:flex-row sm:items-center sm:justify-between ${
            muted
              ? "border-chocolat/10 bg-cream/20 opacity-80"
              : "border-chocolat/10 bg-cream/30"
          }`}
        >
          <div className="flex min-w-0 gap-3">
            {ev.imageUrl ? (
              <EventListThumb src={ev.imageUrl} alt={ev.location} />
            ) : null}
            <div className="min-w-0">
              <p className="text-sm font-semibold text-chocolat">
                {formatEventDate(ev.eventDate)}
                {ev.timeLabel ? ` · ${ev.timeLabel}` : ""}
              </p>
              <p className="font-medium text-chocolat">{ev.location}</p>
              {ev.note ? (
                <p className="text-sm text-muted">{ev.note}</p>
              ) : null}
            </div>
          </div>
          <div className="flex shrink-0 gap-2">
            <button
              type="button"
              onClick={() => onEdit(ev)}
              className="rounded-full border border-chocolat/20 px-4 py-2 text-sm font-medium text-chocolat hover:bg-white"
            >
              Modifier
            </button>
            <button
              type="button"
              onClick={() => onRemove(ev.id)}
              className="rounded-full border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-800"
            >
              Supprimer
            </button>
          </div>
        </li>
      ))}
    </ul>
  );
}

function EventImageField({
  imageUrl,
  uploading,
  onUpload,
  onUrlChange,
  onClear,
}: {
  imageUrl: string;
  uploading: boolean;
  onUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onUrlChange: (url: string) => void;
  onClear: () => void;
}) {
  return (
    <div className="flex flex-col gap-2 sm:col-span-2">
      <span className="text-sm font-medium text-chocolat">
        Photo <span className="font-normal text-muted">(optionnel)</span>
      </span>
      <div className="flex flex-wrap items-end gap-3">
        <label className="inline-flex cursor-pointer items-center rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 text-sm font-medium text-chocolat hover:bg-cream">
          <input
            type="file"
            accept="image/jpeg,image/png,image/webp,image/gif"
            className="sr-only"
            onChange={onUpload}
            disabled={uploading}
          />
          {uploading ? "Envoi…" : "Choisir un fichier"}
        </label>
        <span className="text-xs text-muted">ou colle une URL ci-dessous</span>
      </div>
      <input
        type="text"
        value={imageUrl}
        onChange={(e) => onUrlChange(e.target.value)}
        placeholder="https://… ou /uploads/… ou /gallery/…"
        autoComplete="off"
        className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 text-sm outline-none ring-gaufre/40 focus:ring-2"
      />
      {imageUrl.trim() ? (
        <div className="mt-2 flex items-start gap-3">
          <EventListThumb src={imageUrl} alt="Aperçu" large />
          <button
            type="button"
            onClick={onClear}
            className="text-sm text-red-700 underline"
          >
            Retirer la photo
          </button>
        </div>
      ) : null}
    </div>
  );
}

function EventListThumb({
  src,
  alt,
  large,
}: {
  src: string;
  alt: string;
  large?: boolean;
}) {
  return (
    <div
      className={`relative shrink-0 overflow-hidden rounded-xl border border-chocolat/10 bg-chocolat/5 ${
        large ? "h-20 w-32" : "h-14 w-20"
      }`}
    >
      {src.startsWith("http") ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={src} alt={alt} className="h-full w-full object-cover" />
      ) : (
        <Image
          src={src}
          alt={alt}
          fill
          unoptimized={isUploadAssetPath(src)}
          className="object-cover"
          sizes={large ? "128px" : "80px"}
        />
      )}
    </div>
  );
}

function formatEventDate(iso: string): string {
  const [y, m, d] = iso.split("-").map(Number);
  return new Date(y, m - 1, d).toLocaleDateString("fr-FR", {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  });
}
