import { sendMessage } from '../../socket/socket.tsx';
import { useForm, SubmitHandler } from 'react-hook-form';

type Input = {
  message: string;
};

type MessaFormProps = {
  contact: string;
};

function MessageForm({ contact }: MessaFormProps) {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<Input>();

  // Sending message
  const submitMessage: SubmitHandler<Input> = (data) => {
    console.log(contact);

    // Block sending empty message
    if (!data.message) {
      return;
    }

    sendMessage(data.message, contact);
    reset({ message: '' });
  };

  const adjustSize = (event) => {
    const textarea = event.target;

    // Adjust height
    textarea.style.height = 'auto';
    const maxHeight = 500;

    if (textarea.scrollHeight > maxHeight) {
      textarea.style.height = `${maxHeight}px`;
      textarea.style.overflowY = 'auto';
    } else {
      textarea.style.height = `${textarea.scrollHeight}px`;
      textarea.style.overflowY = 'hidden';
    }
  };

  return (
    <form onSubmit={handleSubmit(submitMessage)}>
      <div className="flex items-end">
        <textarea
          className="resize-none overflow-y-hidden bg-green-50 text-black rounded-md w-full ml-1 mr-1 size-10"
          autoFocus={!!contact}
          disabled={!contact}
          placeholder="Enter message"
          onInput={adjustSize}
          rows={1}
          {...register('message', {
            maxLength: 2000,
            minLength: 1,
          })}
        />
        {errors?.message?.type === 'maxLength' && (
          <p>Maximum length of the message is 2000</p>
        )}
        <button
          className="text-black bg-green-500 hover:bg-green-400 font-bold py-2 px-4 rounded mr-1 w-24"
          type="submit"
        >
          Send
        </button>
      </div>
    </form>
  );
}

export default MessageForm;
