import white_arrow from '../../../../public/assets/interface/white_arrow.svg'
import left_arrow from '../../../../public/assets/interface/left_arrow.svg'
import { InterfaceTextInput } from "@/components/forms/interface_input";
import { ClientContext } from "@/utils/cartProvider";
import { POSTRequest, GETRequest } from "@/utils/requestHeader";
import { Loading } from "@/components/loader";

import { useState, useContext } from "react";
import Image from "next/image";
import { lock } from '@/utils/lockScreen';

import { ForgotPassword } from "./forgotPassword";
import { schemaSignIn } from '../../../../public/assets/yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from "react-hook-form";
import { useRouter } from 'next/router';

// import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react';

const API_URL = process.env.NEXT_PUBLIC_API_URL

export function SignInForm ({formation}) {
    const { v4: uuidv4 } = require('uuid');
    const router = useRouter()
    const { dispatch, client } = useContext(ClientContext);

    const {handleSubmit, register, formState: {errors}} = useForm ({ resolver:  yupResolver(schemaSignIn)})

    const [forgotCard, setForgotCard] = useState(false)
    const [loading, setLoading] = useState(false)
    const [logErr, setlogErr] = useState(false)

    async function onSubmit(data) {
        setlogErr(false)
        setLoading(true)
        const { emailIn, passwordIn } = data
		try {
            const response = await fetch('/api/proxy/auth/client', POSTRequest({ email: emailIn, password:passwordIn }))
            if(response.status !== 200) {
                setLoading(false)
                setlogErr(true)
                return
            }
            const auth = await response.json()
            if(auth.data){
                const check_seance = await fetch(`${API_URL}/api/formations/seances`, GETRequest).then(r => r.json())
                
                if(check_seance.filter(s => new Date(s.beginning_date).getTime() === new Date(client.seance.beginning_date).getTime() && new Date(s.end_date).getTime() === new Date(client.seance.end_date).getTime()).length > 0) {
                    setLoading(false); setlogErr(true); return
                }

                const token_request = await fetch(`${API_URL}/api/auth/google/access_token`, GETRequest)
                const token = await token_request.json()
                
                if(token?.access_token !== null && token?.access_token !== undefined && token?.access_token){
                    // const tutor_email = await fetch(`${API_URL}/api/tutors/${client.tutor_id}`, GETRequest).then(r => r.json())
                    const event = {
                        summary: `[SCRIPTOR] - Séance`,
                        description: `Séance pour la formation ${formation.title}`,
                        start: {
                            dateTime: new Date(client?.seance?.beginning_date).toISOString(),
                            timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
                        },
                        end: {
                            dateTime: new Date(client?.seance?.end_date).toISOString(),
                            timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
                        },
                        conferenceData:{
                            createRequest: {
                                requestId:uuidv4(),
                                conferenceSolutionKey: {
                                    type:'hangoutsMeet'
                                }
                            },
                        },
                        // attendees:[
                        //     { email:tutor_email.email },
                        //     { email: auth.data.email }
                        // ],
                    }
                    const event_request = await fetch(`https://www.googleapis.com/calendar/v3/calendars/primary/events?conferenceDataVersion=1&sendNotifications=true`, {
                        method: "POST",  
                        headers: {
                            'Authorization': `Bearer ${token?.access_token}`,
                        },
                        body:JSON.stringify(event)  
                    })
                    const new_event = await event_request.json()

                    const new_seance = await fetch(`${API_URL}/api/formations/${formation.id}/seances`, POSTRequest({ 
                        tutor_id: client.tutor_id, client_id: auth.data.id,
                        beginning_date: client.seance.beginning_date,
                        end_date: client.seance.end_date,
                        google_meet_link: new_event.hangoutLink,
                        google_event_id: new_event.id
                    }))
                    if(new_seance.status !== 200) {
                        setLoading(false)
                        setlogErr(true)
                        return
                    }
                    const seance = await new_seance.json()
                    const new_order = await fetch(`${API_URL}/api/orders`, POSTRequest({ 
                        tutor_id: client.tutor_id,
                        client_id: auth.data.id,
                        formation_id: formation.id,
                        study_level: client.study_level ? client.study_level : null,
                        study_title: client.study_title ? client.study_title : null,
                        subject_description: client.study_subject ? client.study_subject : null,
                        delay: client.delay ? client.delay : null,
                        comment: client.comment ? client.comment : null,
                        discipline: client.discipline ? client.discipline : null,
                        files: client.files ? client.files : {},
                        word_number: client.word_number ? client.word_number : null,
                        search_hypothesis: client.search_hypothesis ? client.search_hypothesis : null,
                        problematic : client.problematic ? client.problematic : null,
                        questionnaire : client.questionnaire ? client.questionnaire : null,
                        pages: client.pages ? client.pages : null,
                        timing: client.timing ? client.timing : null,
                        presentation_duration : client.presentation_duration ? client.presentation_duration : null,
                        statut: client.statut ? client.statut : null,
                    }))
                    const order = await new_order.json()

                    const add_seance = await fetch(`${API_URL}/api/orders/${order.id}/seances/${seance.id}`, POSTRequest())
                    // const payment_link = await fetch(`${API_URL}/api/orders/${order.id}/stripe/session`, GETRequest)
                    const payment_link = await fetch(`${API_URL}/api/orders/${order.id}/stripe/session`, POSTRequest({ 
                        cancel_url:`https://www.formations.scriptor.fr${router.asPath}`
                    }))
                    const link = await payment_link.json()
                    const url = await link.stripe_session.url
                    if(response.status === 200)  { 
                        location.assign(url)
                    }
                }
            }
            setLoading(false)
		} catch (err) {
            console.error('Request failed:' + err)
            setLoading(false)
		}
	}

    return (
        <>
            <ForgotPassword forgotCard={forgotCard} setForgotCard={setForgotCard} user_type='clients' />
            {logErr ? <div className="text-sm text-[#d32f2f] text-center mb-5">Identifiant(s) incorrect(s) ou problème avec la commande (séance réservé, tuteur indisponible...)</div> : ''}
            {loading 
                ? <Loading />
                : 
                <form onSubmit={handleSubmit(onSubmit)} className="grid grid-cols-2 gap-5 sm:flex sm:flex-col ">
                    <InterfaceTextInput label='Email *' placeholder='Entrez votre email' name="emailIn" options={{...register("emailIn")}} commonError={errors.emailIn} 
                                        commonErrorMessage={errors.emailIn?.message}/>
                    <InterfaceTextInput type="password" label='Mot de passe *' placeholder='Entrez votre mot de passe' name="passwordIn" options={{...register("passwordIn")}} 
                                        commonError={errors.passwordIn} commonErrorMessage={errors.passwordIn?.message}/>
                    <p className='font-normal text-sm underline underline-offset-2 cursor-pointer -mt-2 col-span-2' onClick={() => {setForgotCard(true); window?.scrollTo({top:0}); lock()}}>Mot de passe oublié ?</p>
                    <div className='col-span-2 mt-2 flex justify-between'>
                        <button type='button' onClick={() => {dispatch({type: 'KEEP_STEP', step: 2});location.reload()}} 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'>Payer</p>
                        </button>
                    </div>
                </form>
            }
        </>
    )

}

 