"use client";

import { useActionState } from "react";
import { createAbsenceAction } from "@/lib/actions/absences";
import { ABSENCE_TYPES, ABSENCE_TYPE_LABELS } from "@/lib/absenceConstants";

function todayISO() {
  return new Date().toISOString().slice(0, 10);
}

export function NewAbsenceForm() {
  const [state, formAction, pending] = useActionState(createAbsenceAction, {});

  return (
    <form
      action={formAction}
      className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-6 flex flex-col gap-4 mb-8"
    >
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-[var(--rk-ink-muted)]">Art</span>
          <select
            name="type"
            defaultValue="vacation"
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
          >
            {ABSENCE_TYPES.map((t) => (
              <option key={t} value={t}>
                {ABSENCE_TYPE_LABELS[t]}
              </option>
            ))}
          </select>
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="text-[var(--rk-ink-muted)]">Von</span>
          <input
            type="date"
            name="startDate"
            defaultValue={todayISO()}
            required
            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-[var(--rk-ink-muted)]">Bis</span>
          <input
            type="date"
            name="endDate"
            defaultValue={todayISO()}
            required
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
          />
        </label>
      </div>

      <label className="flex flex-col gap-1.5 text-sm">
        <span className="text-[var(--rk-ink-muted)]">Notiz (optional)</span>
        <input
          name="note"
          placeholder="z. B. Vertretung durch …"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
        />
      </label>

      <div className="flex items-center gap-3">
        <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"
        >
          Abwesenheit eintragen
        </button>
        {state.error && <span className="text-sm text-red-400">{state.error}</span>}
      </div>
    </form>
  );
}
