"use client";

import { useActionState } from "react";
import { createIntranetArticleAction } from "@/lib/actions/intranet";

export function NewIntranetArticleForm({ departments }: { departments: { id: string; name: string; color: string }[] }) {
  const [state, formAction, pending] = useActionState(createIntranetArticleAction, {});

  return (
    <form action={formAction} className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 flex flex-col gap-3 mb-8">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <input
          name="title"
          placeholder="Titel, z. B. Ablauf bei Convention-Shootings"
          required
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
        />
        <input
          name="category"
          placeholder="Kategorie, z. B. Shootings"
          defaultValue="Allgemein"
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
        />
      </div>
      <textarea
        name="content"
        placeholder="Inhalt"
        required
        rows={6}
        className="bg-transparent border border-white/15 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-white/50 resize-y"
      />

      {departments.length > 0 && (
        <div>
          <p className="text-xs text-[var(--rk-ink-muted)] mb-1.5">
            Nur für bestimmte Abteilungen sichtbar (nichts ankreuzen = für alle):
          </p>
          <div className="flex flex-wrap gap-2">
            {departments.map((d) => (
              <label
                key={d.id}
                className="flex items-center gap-1.5 text-xs border rounded-full px-2.5 py-1 cursor-pointer"
                style={{ borderColor: `${d.color}66` }}
              >
                <input type="checkbox" name="departmentIds" value={d.id} className="h-3 w-3" />
                <span style={{ color: d.color }}>{d.name}</span>
              </label>
            ))}
          </div>
        </div>
      )}

      <div className="flex items-center gap-5">
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" name="visible" defaultChecked className="h-3.5 w-3.5" />
          Sofort für alle Mitarbeiter:innen sichtbar
        </label>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" name="pinned" className="h-3.5 w-3.5" />
          📌 Anpinnen (oben anzeigen)
        </label>
      </div>
      <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"
      >
        Beitrag anlegen
      </button>
      {state.error && <p className="text-sm text-red-400">{state.error}</p>}
    </form>
  );
}
