"use client";

import { useEffect } from "react";
import { useActionState } from "react";
import { useRouter } from "next/navigation";
import { createTodoAction } from "@/lib/actions/todos";
import { PRIORITY_LABELS } from "@/lib/todoConstants";
import { TagInput } from "@/components/admin/TagInput";
import { TodoPeoplePicker } from "@/components/admin/TodoPeoplePicker";
import { TodoRecurrenceFields } from "@/components/admin/TodoRecurrenceFields";
import type { StaffOption, OrderOption } from "@/components/admin/TodoBoard";
import type { TodoPriority } from "@/models/Todo";

export function NewTodoForm({
  staffList,
  orderOptions,
  viewerId,
  canCreateForOthers,
  onDone,
}: {
  staffList: StaffOption[];
  orderOptions: OrderOption[];
  viewerId: string;
  canCreateForOthers: boolean;
  onDone: () => void;
}) {
  const [state, formAction, pending] = useActionState(createTodoAction, {});
  const router = useRouter();

  useEffect(() => {
    if (state.success) {
      router.refresh();
      onDone();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.success]);

  return (
    <form action={formAction} className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 flex flex-col gap-3">
      <label className="flex flex-col gap-1.5 text-sm">
        <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Titel</span>
        <input
          name="title"
          required
          maxLength={200}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
        />
      </label>
      <label className="flex flex-col gap-1.5 text-sm">
        <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Beschreibung (optional)</span>
        <textarea
          name="description"
          rows={2}
          maxLength={4000}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50 resize-y"
        />
      </label>
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Zuständig</span>
          <select
            name="assignedToId"
            defaultValue={viewerId}
            disabled={!canCreateForOthers}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50 disabled:opacity-60"
          >
            {staffList.map((s) => (
              <option key={s.id} value={s.id}>
                {s.id === viewerId ? `${s.name} (ich)` : s.name}
              </option>
            ))}
          </select>
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Priorität</span>
          <select
            name="priority"
            defaultValue="normal"
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
          >
            {(Object.keys(PRIORITY_LABELS) as TodoPriority[]).map((p) => (
              <option key={p} value={p}>
                {PRIORITY_LABELS[p]}
              </option>
            ))}
          </select>
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Fällig am (optional)</span>
          <input
            type="date"
            name="dueDate"
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
          />
        </label>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Labels (optional)</span>
          <TagInput name="labels" placeholder="Label eingeben, dann Enter" />
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Projekt / Liste (optional)</span>
          <input
            name="project"
            maxLength={80}
            placeholder="z. B. DoKomi 2027"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
          />
        </label>
      </div>
      {canCreateForOthers && (
        <details className="rounded-lg border border-white/10 p-3">
          <summary className="cursor-pointer text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
            Weitere Personen (optional)
          </summary>
          <div className="mt-3 flex flex-col gap-3">
            <div>
              <p className="mb-1.5 text-xs text-[var(--rk-ink-muted)]">Weitere Zuständige (dürfen mitbearbeiten)</p>
              <TodoPeoplePicker name="additionalAssigneeIds" staffList={staffList} />
            </div>
            <div>
              <p className="mb-1.5 text-xs text-[var(--rk-ink-muted)]">Beobachter (nur Benachrichtigungen)</p>
              <TodoPeoplePicker name="watcherIds" staffList={staffList} />
            </div>
          </div>
        </details>
      )}
      <label className="flex flex-col gap-1.5 text-sm">
        <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
          Unteraufgaben (optional, eine pro Zeile)
        </span>
        <textarea
          name="subtasks"
          rows={3}
          placeholder={"Referenzbilder sammeln\nKostüm prüfen\nEquipment packen"}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50 resize-y"
        />
      </label>
      <TodoRecurrenceFields />
      {orderOptions.length > 0 && (
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">Auftragsbezug (optional)</span>
          <select
            name="orderId"
            defaultValue=""
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
          >
            <option value="">Kein Auftrag</option>
            {orderOptions.map((o) => (
              <option key={o.id} value={o.id}>
                {o.label}
              </option>
            ))}
          </select>
        </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"
      >
        {pending ? "…" : "Anlegen"}
      </button>
      {state.error && <p className="text-sm text-red-400">{state.error}</p>}
    </form>
  );
}
