import React from 'react';

const SendNote = ({ setNoteSubmit, setSendNoteClose }) => {
  const [noteContent, setNoteContent] = React.useState('');
  const [remainingCharCount, setRemainingCharCount] = React.useState(3000);
  const [submitDisabled, setSubmitDisabled] = React.useState(false);

  const handleNoteSubmit = (e) => {
    e.preventDefault();
    setNoteSubmit(noteContent);
    setNoteContent('');
  };

  const handleNoteCancel = (e) => {
    e.preventDefault();
    setNoteContent('');
    setSendNoteClose(true);
  };

  const handleNoteChange = (e) => {
    if (Number(e.target.value.length) > 3000) {
      setSubmitDisabled(true);
      setRemainingCharCount(0);
    } else {
      setSubmitDisabled(false);
      setRemainingCharCount(3000 - Number(e.target.value.length));
    }
    setNoteContent(e.target.value);
  };

  return (
    <form>
      <div className='mt-6 flex justify-end'>
        <div className='w-full md:w-1/2'>
          <label
            className='mb-2 block text-sm font-bold text-gray-100'
            htmlFor='note'
          >
            Notes
          </label>
          <textarea
            className='h-44 w-full rounded-md border border-gray-500 bg-gray-700 p-2 text-white shadow placeholder:text-gray-200'
            placeholder='Type your note here...'
            value={noteContent}
            onChange={(e) => handleNoteChange(e)}
          ></textarea>
          <span className='text-sm text-red-500'>
            {remainingCharCount} characters remaining
          </span>
        </div>
      </div>
      <div className='flex flex-row justify-end gap-2'>
        {!submitDisabled && (
          <button
            className='focus:shadow-outline mt-2 w-min rounded bg-green-500 px-4 py-2 text-sm font-bold text-white hover:bg-green-700 focus:outline-none'
            type='button'
            onClick={(e) => handleNoteSubmit(e)}
          >
            Send
          </button>
        )}
        <button
          className='focus:shadow-outline mt-2 w-min rounded bg-red-500 px-4 py-2 text-sm font-bold text-white hover:bg-red-700 focus:outline-none'
          type='button'
          onClick={(e) => handleNoteCancel(e)}
        >
          Cancel
        </button>
      </div>
    </form>
  );
};

export default SendNote;
