'use client';

import { useActionState, useEffect, useRef } from 'react';
import { createContactAction } from '../app/actions';

type Props = {
  labels: {
    name: string;
    phoneNumber: string;
    email: string;
    company: string;
    notes: string;
    submit: string;
    success: string;
  };
};

type ContactFormState = {
  error?: string;
  success?: string;
};

const initialState: ContactFormState = {};

export function ContactForm({ labels }: Props) {
  const [state, formAction, pending] = useActionState(createContactAction, initialState);
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (state.success) {
      formRef.current?.reset();
    }
  }, [state.success]);

  return (
    <form action={formAction} className="stack-form card" ref={formRef}>
      <input name="name" placeholder={labels.name} required />
      <input name="phoneNumber" placeholder={labels.phoneNumber} required />
      <input name="email" placeholder={labels.email} type="email" />
      <input name="company" placeholder={labels.company} />
      <textarea name="notes" placeholder={labels.notes} rows={4} />
      <button type="submit" disabled={pending}>
        {pending ? '...' : labels.submit}
      </button>
      {state.error ? <p className="form-error">{state.error}</p> : null}
      {state.success ? <p className="form-success">{labels.success}</p> : null}
    </form>
  );
}
