'use client';

import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useFormState, useFormStatus } from 'react-dom';
import { replyToConversation, type ReplyState } from '@/app/account/messages/actions';

const initialState: ReplyState = undefined;

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} className="btn-primary shrink-0 disabled:opacity-60">
      {pending ? 'Sending…' : 'Send'}
    </button>
  );
}

export function ReplyForm({ conversationId }: { conversationId: number }) {
  const action = replyToConversation.bind(null, conversationId);
  const [state, formAction] = useFormState(action, initialState);
  const router = useRouter();
  const formRef = useRef<HTMLFormElement>(null);
  const errors = state?.errors ?? {};

  useEffect(() => {
    if (state?.success) {
      formRef.current?.reset();
      router.refresh();
    }
    // Only re-run when the action's result actually changes.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state]);

  return (
    <form ref={formRef} action={formAction} className="mt-4">
      {Object.keys(errors).length > 0 && (
        <p className="mb-2 text-xs text-red-600">{Object.values(errors).flat()[0]}</p>
      )}
      <div className="flex items-end gap-3">
        <textarea
          name="message"
          rows={2}
          required
          maxLength={2000}
          placeholder="Type a message…"
          className="flex-1 rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
        />
        <SubmitButton />
      </div>
    </form>
  );
}
