"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
  updateConventionAction,
  deleteConventionAction,
  setConventionVisibleAction,
  reopenSlotsAndNotifyWaitlistAction,
  joinConventionAction,
  leaveConventionAction,
  assignStaffToConventionAction,
  removeStaffFromConventionAction,
  removeConventionMediaAction,
} from "@/lib/actions/conventions";
import { formatDateDE } from "@/lib/orderConstants";

type StaffOption = { id: string; name: string };

export function ConventionRow({
  item,
  viewerId,
  canEditOthers,
  staffOptions,
}: {
  item: {
    id: string;
    name: string;
    location: string;
    startDate: string;
    endDate: string;
    infoUrl: string;
    slotsAvailable: boolean;
    notes: string;
    notesEn: string;
    image: string;
    logo: string;
    visible: boolean;
    waitlistCount: number;
    assignedStaff: StaffOption[];
  };
  viewerId: string;
  canEditOthers: boolean;
  staffOptions: StaffOption[];
}) {
  const [pending, startTransition] = useTransition();
  const [mediaError, setMediaError] = useState<string | null>(null);
  const router = useRouter();
  const isAssigned = item.assignedStaff.some((s) => s.id === viewerId);
  const assignableOptions = staffOptions.filter((s) => !item.assignedStaff.some((a) => a.id === s.id));

  function submit(form: HTMLFormElement) {
    const data = new FormData(form);
    startTransition(async () => {
      await updateConventionAction(item.id, data);
      router.refresh();
    });
  }

  function removeMedia(kind: "image" | "logo") {
    setMediaError(null);
    startTransition(async () => {
      const res = await removeConventionMediaAction(item.id, kind);
      if (res?.error) {
        setMediaError(res.error);
        return;
      }
      router.refresh();
    });
  }

  const dateLabel =
    item.startDate === item.endDate
      ? formatDateDE(new Date(item.startDate))
      : `${formatDateDE(new Date(item.startDate))} – ${formatDateDE(new Date(item.endDate))}`;

  return (
    <details className={`bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 ${item.visible ? "" : "opacity-60"}`}>
      <summary className="flex items-center justify-between gap-3 cursor-pointer list-none">
        <div className="min-w-0">
          <p className="text-sm truncate">
            {item.name}
            {item.location && <span className="text-[var(--rk-ink-muted)]"> · {item.location}</span>}
          </p>
          <p className="text-xs text-[var(--rk-ink-muted)]">
            {dateLabel} · {item.slotsAvailable ? "Slots frei" : "Warteliste"}
            {item.waitlistCount > 0 && ` (${item.waitlistCount} auf Warteliste)`}
            {" · Team: "}
            {item.assignedStaff.length > 0 ? item.assignedStaff.map((s) => s.name).join(", ") : "niemand eingetragen"}
            {" · Bearbeiten ▾"}
          </p>
        </div>
        <div className="flex items-center gap-3 shrink-0" onClick={(e) => e.stopPropagation()}>
          {!item.slotsAvailable && item.waitlistCount > 0 && (
            <button
              disabled={pending}
              onClick={() => {
                if (confirm(`Slots für „${item.name}" wieder öffnen und ${item.waitlistCount} Wartende benachrichtigen?`)) {
                  startTransition(async () => { await reopenSlotsAndNotifyWaitlistAction(item.id); router.refresh(); });
                }
              }}
              className="text-xs border border-emerald-400/40 text-emerald-400 rounded-lg px-3 py-1.5 hover:border-emerald-400 disabled:opacity-50"
            >
              Warteliste benachrichtigen
            </button>
          )}
          <label className="flex items-center gap-1.5 text-xs">
            <input
              type="checkbox"
              checked={item.visible}
              disabled={pending}
              onChange={(e) => startTransition(async () => { await setConventionVisibleAction(item.id, e.target.checked); router.refresh(); })}
              className="h-3.5 w-3.5"
            />
            Sichtbar
          </label>
          <button
            disabled={pending}
            onClick={() => {
              if (confirm(`Convention „${item.name}" wirklich löschen?`)) {
                startTransition(async () => { await deleteConventionAction(item.id); router.refresh(); });
              }
            }}
            className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
          >
            Löschen
          </button>
        </div>
      </summary>

      <div className="mt-4 pt-4 border-t border-white/10" onClick={(e) => e.stopPropagation()}>
        <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-2">Team vor Ort</p>
        <div className="flex flex-wrap items-center gap-2 mb-2">
          {item.assignedStaff.length === 0 && <span className="text-xs text-[var(--rk-ink-muted)]">Noch niemand eingetragen.</span>}
          {item.assignedStaff.map((s) => (
            <span
              key={s.id}
              className="inline-flex items-center gap-1.5 text-xs border border-white/15 rounded-full px-2.5 py-1"
            >
              {s.name}
              {(s.id === viewerId || canEditOthers) && (
                <button
                  type="button"
                  disabled={pending}
                  onClick={() =>
                    startTransition(async () => {
                      if (s.id === viewerId) await leaveConventionAction(item.id);
                      else await removeStaffFromConventionAction(item.id, s.id);
                      router.refresh();
                    })
                  }
                  className="text-[var(--rk-ink-muted)] hover:text-red-400 disabled:opacity-50"
                  title="Entfernen"
                >
                  ×
                </button>
              )}
            </span>
          ))}
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {!isAssigned && (
            <button
              type="button"
              disabled={pending}
              onClick={() => startTransition(async () => { await joinConventionAction(item.id); router.refresh(); })}
              className="text-xs border border-emerald-400/40 text-emerald-400 rounded-lg px-3 py-1.5 hover:border-emerald-400 disabled:opacity-50"
            >
              Ich bin dabei
            </button>
          )}
          {canEditOthers && assignableOptions.length > 0 && (
            <select
              defaultValue=""
              disabled={pending}
              onChange={(e) => {
                const staffId = e.target.value;
                if (!staffId) return;
                startTransition(async () => { await assignStaffToConventionAction(item.id, staffId); router.refresh(); });
                e.target.value = "";
              }}
              className="bg-transparent border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
            >
              <option value="" disabled>
                Weitere Person zuteilen …
              </option>
              {assignableOptions.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name}
                </option>
              ))}
            </select>
          )}
        </div>
      </div>

      {item.waitlistCount > 0 && (
        <p className="mt-4 border-t border-white/10 pt-4 text-xs text-[var(--rk-ink-muted)]">
          {item.waitlistCount} {item.waitlistCount === 1 ? "Person wartet" : "Personen warten"} auf einen Slot —
          abarbeiten im Tab <span className="text-[var(--rk-ink)]">Warteliste</span>.
        </p>
      )}

      <form
        onSubmit={(e) => {
          e.preventDefault();
          submit(e.currentTarget);
        }}
        className="mt-4 flex flex-col gap-3"
      >
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <input
            name="name"
            defaultValue={item.name}
            placeholder="Name"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
          <input
            name="location"
            defaultValue={item.location}
            placeholder="Ort"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <label className="flex flex-col gap-1 text-xs">
            <span className="text-[var(--rk-ink-muted)]">Start</span>
            <input
              name="startDate"
              type="date"
              defaultValue={item.startDate.slice(0, 10)}
              className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
            />
          </label>
          <label className="flex flex-col gap-1 text-xs">
            <span className="text-[var(--rk-ink-muted)]">Ende</span>
            <input
              name="endDate"
              type="date"
              defaultValue={item.endDate.slice(0, 10)}
              className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
            />
          </label>
        </div>
        <input
          name="infoUrl"
          defaultValue={item.infoUrl}
          placeholder="Link zur Convention-Website"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
        />
        <input
          name="notes"
          defaultValue={item.notes}
          placeholder="Hinweis (Deutsch)"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
        />
        <input
          name="notesEn"
          defaultValue={item.notesEn}
          placeholder="Hinweis (Englisch, optional)"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
        />
        <div className="flex flex-col gap-2">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
            Foto — Hintergrund der „nächste Convention"-Karte auf der öffentlichen Seite
          </span>
          {item.image && (
            <div className="flex items-center gap-3">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={item.image}
                alt=""
                className="h-20 w-36 rounded-lg border border-white/15 object-cover"
              />
              <button
                type="button"
                disabled={pending}
                onClick={() => removeMedia("image")}
                className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
              >
                Foto entfernen
              </button>
            </div>
          )}
          <input
            name="image"
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="text-sm"
          />
          <span className="text-xs text-[var(--rk-ink-muted)]">
            {item.image
              ? "Neue Datei wählen und speichern ersetzt das Foto in einem Schritt."
              : "Ohne Foto zeigt die Seite ein Standardbild."}
          </span>
        </div>
        <div className="flex flex-col gap-2">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
            Logo — wird über der freien Fläche der Foto-Karte eingeblendet (darf länglich sein, Transparenz bleibt erhalten)
          </span>
          {item.logo && (
            <div className="flex items-center gap-3">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={item.logo}
                alt=""
                className="h-16 w-auto max-w-[12rem] rounded-lg border border-white/15 bg-[var(--rk-bg)] object-contain p-2"
              />
              <button
                type="button"
                disabled={pending}
                onClick={() => removeMedia("logo")}
                className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
              >
                Logo entfernen
              </button>
            </div>
          )}
          <input
            name="logo"
            type="file"
            accept="image/jpeg,image/png,image/webp,image/svg+xml"
            className="text-sm"
          />
          <span className="text-xs text-[var(--rk-ink-muted)]">
            {item.logo
              ? "Neue Datei wählen und speichern ersetzt das Logo in einem Schritt."
              : "Ohne Logo bleibt die Foto-Karte wie sie ist."}
          </span>
        </div>
        {mediaError && <p className="text-xs text-red-400">{mediaError}</p>}
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" name="slotsAvailable" defaultChecked={item.slotsAvailable} className="h-3.5 w-3.5" />
          Slots frei (sonst Warteliste)
        </label>
        <button
          type="submit"
          disabled={pending}
          className="self-start border border-white/30 rounded-lg px-4 py-2 text-xs uppercase tracking-[0.15em] hover:border-white disabled:opacity-50"
        >
          Speichern
        </button>
      </form>
    </details>
  );
}
