import { useContext, useRef, useState } from 'preact/hooks';
import { FaPlus, FaTimes } from 'react-icons/fa';
import { MdSend } from 'react-icons/md';
import { Pb } from '../../EspaceMembres';
import { CurrentChannel } from '../Home';

export default function NewMessage() {
  const [message, setMessage] = useState('');
  const [image, setImage] = useState('');
  const pb = useContext(Pb);
  const [preview, setPreview] = useState('');
  const imageRef = useRef<HTMLInputElement>(null);
  const { get } = useContext(CurrentChannel);

  const handleImageSelect = (e: any) => {
    setImage(e.target.value);
    const file = e.target.files[0];
    if (file) {
      const src = URL.createObjectURL(file);
      setPreview(src);
    }
  };

  const handleSubmit = (e: any) => {
    e.preventDefault();
    if (message.trim().length === 0 && image.trim().length === 0) {
      return;
    }

    const data = new FormData(e.target as HTMLFormElement);

    //send message with image to pb
    pb.collection('messages').create({
      content: message,
      image: data.get('image'),
      channel: get().id,
      author: pb.authStore.model?.id,
    }).then(() => {
      setMessage('');
      setImage('');
      setPreview('');
      if (imageRef.current) {
        imageRef.current.value = '';
      }
      const event = new Event('newMessage');
      document.dispatchEvent(event);
    });

  };

  const handleRemoveImage = () => {
    setImage('');
    setPreview('');
  };

  const handleInutChange = (e: any) => {
    setMessage(e.target.value);
  }

  return (
    <footer className="new-message z-10 flex justify-center w-full">
      <div className="w-full max-w-3xl">
        {preview !== '' && (
          <div className="image-preview w-fit pb-2 absolute bottom-20">
            <img src={preview} alt="Image" className="max-w-xs max-h-48 border-2 border-gray-500" />
            <span className="rounded-full text-gray-800 bg-grey-dark text-lg p-2 block absolute -top-5 -right-5 bg-white cursor-pointer border border-slate-800 hover:text-gray-600 hover:border-gray-600 transition-all" onClick={handleRemoveImage}>
              <FaTimes className="" />
            </span>
          </div>
        )}
        <form
          onSubmit={handleSubmit}
          className="flex gap-2p-2 border border-gray-500 mx-2 sm:p-3 md:mx-0"
        >
          <div className="file">
            <label htmlFor="image" className="cursor-pointer block p-2">
              <span className="rounded-full text-white bg-gray-800 text-lg p-2 block">
                <FaPlus className="" />
              </span>
              <span className="sr-only">Ajouter une image</span>
            </label>
            <input
              type="file"
              name="image"
              id="image"
              accept="image/*"
              className="hidden"
              {...(image !== '' && { value: image })}
              onChange={handleImageSelect}
              ref={imageRef}
            />
          </div>

          <div className="new-message flex-grow">
            <input
              type="text"
              value={message}
              onChange={handleInutChange}
              placeholder="Écrivez votre message..."
              className="text-gray-800 p-2.5 w-full placeholder-gray-400 text-2xl focus:outline-none"
              id="content"
              name="content"
            />
            <label htmlFor="content" className="sr-only">
              Écrivez votre message...
            </label>
          </div>
          <button
            type="submit"
            className="py-2 px-4 text-3xl font-medium text-gray-800 hover:bg-white hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2"
          >
            <span className="sr-only">Envoyer</span>
            <MdSend className="fill-current" />
          </button>
        </form>
      </div>
    </footer>
  );
};
