import React, {useState, ReactNode, useContext} from 'react';
import { useDropzone } from 'react-dropzone';
import { useNavigate, useSearchParams } from 'react-router-dom';
import AuthContext from "../../../../../context/auth-context";
import { toastError, toastSuccess } from '../../../../../services/toaster';
import { uploadImage, getProfilePicture } from '../../../../../API/user';
import UploadPlaceholder from '../../../../SVG/UploadPlaceholder';
import FormButtonBack from '../../../../UI/FormButton/FormButtonBack';
import FormButtonSubmit from '../../../../UI/FormButton/FormButtonSubmit';
import './DragAndDropComponent.scss';

type DropzoneProps = {
    children?: ReactNode
}

function DragAndDropComponent() {
    const {userAvatar, setUserAvatar} = useContext(AuthContext)
    const [imagePreview, setImagePreview] = useState<File  | null>(null);
    const navigate = useNavigate();
    const activeRole = useSearchParams()[0].get('activeRole');

    // Get and handle dropped files

    const { getRootProps, getInputProps } = useDropzone({
      onDrop: (acceptedFiles) => {
      const file = acceptedFiles[0];
      setImagePreview(file);
      }
    });

    // Clear uploaded image

    const clearPreviewImg = () => {
        setImagePreview(null);
    };

    //Handle image submission

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!imagePreview) return;

        //Convert image file to webP and submit

        try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
        
            if (ctx) {
              const image = new Image();
        
              image.onload = async () => {
                canvas.width = image.width;
                canvas.height = image.height;
                ctx.drawImage(image, 0, 0);
        
                canvas.toBlob(async (blob) => {
                  if (blob) {
                    const webpDataUrl = canvas.toDataURL('image/webp');
                    const webpFile = new File([blob], 'image.webp', { type: 'image/webp' });
        
                    let formData = new FormData();
                    formData.append('upload', webpFile);
        
                    const res = await uploadImage(formData);
                    toastSuccess('Η εικόνα σας αποθηκεύτηκε επιτυχώς');
                    setUserAvatar(webpFile);
                    navigate({
                      pathname: '../',
                      search: `?activeRole=${activeRole}`,
                    });
                  }
                }, 'image/webp');
              };
        
              image.src = URL.createObjectURL(imagePreview);
            }
        }
        catch (e){
            toastError('Κάτι πήγε στραβά');
        }
    };
  
    return (
        <form onSubmit={ (e)=>{
            handleSubmit(e);
        }}>
            <div id={'avatardropzone'}> <div {...getRootProps()} className="dropzone">
                {
                    imagePreview
                        ?
                        <div className='preview-container'>
                            <img src={URL.createObjectURL(imagePreview)} alt="Preview" className="preview-image" />
                            <button onClick={(e) => {
                                e.stopPropagation();
                                clearPreviewImg();
                            }}>ΔΙΑΓΡΑΦΗ ΦΩΤΟΓΡΑΦΙΑΣ</button>
                        </div>
                        :
                        <div className="avatar-placeholder-container">
                            <UploadPlaceholder/>
                        </div>
                }

                <input {...getInputProps()} />
                <p>DROP FILE HERE <span>OR</span> SELECT FROM PC</p>
            </div></div>

            <div className='form-btn-container'>
                <FormButtonBack onClick={() => {
                        navigate({
                        pathname: '../',
                        search: `?activeRole=${activeRole}`,
                    });
                }} buttonType='button'>Πίσω</FormButtonBack>
                <FormButtonSubmit buttonType='submit'>ΥΠΟΒΟΛΗ</FormButtonSubmit>
            </div>
        </form>
    );
  }
  
  export default DragAndDropComponent;