"use client";

import { useActionState, useEffect } from "react";
import { updateConfessionAction } from "@/lib/admin/actions";
import type { ActionState } from "@/lib/auth/actions";
import { RichTextEditor } from "@/components/confessions/RichTextEditor";

export function AdminConfessionEditForm({
  confessionId,
  title,
  body,
  visibility,
  onDone,
}: {
  confessionId: string;
  title: string;
  body: string;
  visibility: "ACIK" | "GIZLI";
  onDone: () => void;
}) {
  const updateWithId = updateConfessionAction.bind(null, confessionId);
  const [state, formAction, pending] = useActionState<ActionState, FormData>(updateWithId, undefined);
  const succeeded = state?.message === "İtiraf güncellendi.";

  useEffect(() => {
    if (succeeded) onDone();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [succeeded]);

  return (
    <form action={formAction} className="rounded-xl border border-accent/30 bg-bg-alt p-4">
      <div className="mb-3">
        <label className="mb-1 block text-[12px] font-semibold text-text-muted">Başlık</label>
        <input
          name="title"
          maxLength={100}
          defaultValue={title}
          required
          className="w-full rounded-xl border border-border px-4 py-2.5 text-[14px] outline-none focus:border-accent"
        />
      </div>

      <div>
        <label className="mb-1 block text-[12px] font-semibold text-text-muted">İtiraf metni</label>
        <RichTextEditor name="body" defaultValue={body} />
      </div>

      <div className="mt-3 flex items-center gap-4">
        <label className="flex items-center gap-1.5 text-[13px] font-semibold">
          <input type="radio" name="visibility" value="ACIK" defaultChecked={visibility === "ACIK"} className="accent-accent" />
          Açık
        </label>
        <label className="flex items-center gap-1.5 text-[13px] font-semibold">
          <input type="radio" name="visibility" value="GIZLI" defaultChecked={visibility === "GIZLI"} className="accent-accent" />
          Gizli (isim maskelenir)
        </label>
      </div>

      {state?.message && state.message !== "İtiraf güncellendi." && (
        <p className="mt-2 text-[13px] text-accent">{state.message}</p>
      )}

      <div className="mt-3 flex gap-2">
        <button type="submit" disabled={pending} className="rounded-lg bg-accent px-4 py-2 text-[12.5px] font-semibold text-white disabled:opacity-60">
          {pending ? "Kaydediliyor..." : "Kaydet"}
        </button>
        <button type="button" onClick={onDone} className="rounded-lg bg-white px-4 py-2 text-[12.5px] font-semibold text-text-muted hover:bg-bg">
          Vazgeç
        </button>
      </div>
    </form>
  );
}
