import Image from 'next/image'
import white_arrow from '../../../../public/assets/interface/white_arrow.svg'
import left_arrow from '../../../../public/assets/interface/left_arrow.svg'

import { InterfaceTextArea } from '@/components/forms/interface_input'
import { useState, useContext, useEffect } from 'react'
import { ClientContext } from '@/utils/cartProvider'

import { useForm } from "react-hook-form";
import { schemaInscription22 } from '../../../../public/assets/yup'
import { yupResolver } from '@hookform/resolvers/yup';
import { InterfaceFiles } from '@/components/forms/interface_input'

const API_URL = process.env.NEXT_PUBLIC_API_URL

export default function Form22 () {
    const [docId, setDocId] = useState([])
    const [targetFile, setTargetFile] = useState()
    const [currentType, setCurrentType] = useState()
    const [submitLoading, setSubmitLoading] = useState(false)

    async function uploadFile(e, fileT){
        const formData2 = new FormData();
        if(e?.target?.files.length > 0) {
            formData2.append("file[]", e?.target?.files[0]);
        } else {    
            return
        }
        setSubmitLoading(true)
        try {
            const form = await fetch(`${API_URL}/api/files/upload`, {method: "POST", mode: "cors", body: formData2})
            const register = await form.json()
            setDocId([
                ...docId?.filter(file => file?.title !== fileT),
                {id:register[0].id, url:register[0].download_url, title:fileT}
            ])
            setSubmitLoading(false)
        } catch (err) {
            setSubmitLoading(false)
            console.error('Request failed:' + err.message)
        }
    }
    
    useEffect(() => {
        uploadFile(targetFile, currentType)
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [targetFile, currentType])
    
   
    const { dispatch } = useContext(ClientContext);
    const updateClient = (delay, files, comment) => {
        dispatch({
            type: 'UPDATE_CART1',
            delay: delay,
            files: files,
            comment: comment,
        })
    }

    const {handleSubmit, register, formState: {errors}} = useForm({resolver: yupResolver(schemaInscription22)})
    function onSubmit(data) {
        let newObj = {}
        for(let file of docId) {
            newObj[file.id] = {title: file.title}
        }
        const {delay, comment} = data
        updateClient(delay, newObj, comment)
        dispatch({
            type: 'KEEP_STEP',
            step: 2
        })
        window?.scrollTo({top:700,behavior: "smooth"})
    }

    return(
        <form onSubmit={handleSubmit(onSubmit)} className='grid grid-cols-2 gap-5 w-[600px] rounded-xl sm:flex sm:flex-col sm:w-[80vw] 2sm:w-[90vw]'>
                <InterfaceFiles fileType='Agrément' label='Demande / Retour d’agrément' docId={docId} setCurrentType={setCurrentType} setTargetFile={setTargetFile} setDocId={setDocId} submitLoading={submitLoading} />
                <InterfaceFiles  fileType='Ebauche' label={`Ebauche de l'avancement`} docId={docId} setCurrentType={setCurrentType} setTargetFile={setTargetFile} setDocId={setDocId} submitLoading={submitLoading} />
                <InterfaceTextArea label='Commentaire / Consignes' height={6} placeholder={`Merci de bien vouloir renseigner toute information utile à la mission.`} name="comment"  options={{...register("comment")}} commonError={errors.comment} commonErrorMessage={errors.comment?.message}/>                
                <div className='col-span-2 mt-2 flex justify-between'>
                    <button type='button' onClick={() => {dispatch({type: 'KEEP_STEP', step: 0})}} className='px-[25px] flex gap-3 rounded-xl py-5 bg-[#2A3955]'>
                        <Image src={left_arrow} alt="Arrow icon" priority />
                        <p className='font-bold'>Précédent</p>
                    </button>
                    <button type='submit' className='px-[25px] flex gap-3 rounded-xl py-5 bg-[#2A3955]'>
                        <Image src={white_arrow} alt="Arrow icon" priority />
                        <p className='font-bold'>Suivant</p>
                    </button>
                </div>
        </form>
    )
}