import { useForm, SubmitHandler } from 'react-hook-form';
import { sendContact } from '../../api/contactsApi.tsx';

type Input = {
  contact: string;
};

type ContactsProps = {
  usernamecontact: string;
  read: boolean;
};

type ContactFormProps = {
  InitializeContact: (contact: string) => void;
  setContactsList: React.Dispatch<React.SetStateAction<ContactsProps[]>>;
};

function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
  const { register, handleSubmit, reset } = useForm<Input>();

  const submitContact: SubmitHandler<Input> = (data) => {
    const contact = data.contact.trim();
    setContactsList((prevContacts) => {
      if (!prevContacts.some((c) => c.usernamecontact === contact)) {
        sendContact(contact);
        InitializeContact(contact);
        return [...prevContacts, { usernamecontact: contact, read: true }];
      }
      return prevContacts;
    });

    reset({ contact: '' });
  };
  return (
    <>
      <div className="text-center">
        <form onSubmit={handleSubmit(submitContact)}>
          <input
            className="text-black bg-green-50 pl-2 shadow-lg rounded-md h-8 mb-2 mt-2"
            type="text"
            placeholder="Enter contact"
            {...register('contact', {
              // valid username length (validated on signup)
              minLength: 4,
              maxLength: 20,
            })}
          />
        </form>
      </div>
    </>
  );
}

export default ContactForm;
