import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import { useState, useContext, useRef } from "react";
import { InterfaceTextInput } from "@/components/forms/interface_input";
import { Loading } from "@/components/loader";
import { POSTRequest, GETRequest } from "@/utils/requestHeader";
import white_arrow from '../../../../public/assets/interface/white_arrow.svg'
import Image from "next/image";
import { schemaSignUp } from "../../../../public/assets/yup";
import { ClientContext } from '@/utils/cartProvider'
import { useRouter } from 'next/router';
import Link from "next/link";

import ReCAPTCHA from "react-google-recaptcha"

const API_URL = process.env.NEXT_PUBLIC_API_URL
const SITE_KEY = process.env.NEXT_PUBLIC_SITE_KEY

export function SignUpForm ({formation}) {
    const router = useRouter()
    const { v4: uuidv4 } = require('uuid');
    const  {handleSubmit, register, formState: {errors}} = useForm ({ resolver:  yupResolver(schemaSignUp)})
    const [loading, setLoading] = useState(false)
    const [logErr, setlogErr] = useState(false)
    const [logErrAccount, setlogErrAccount] = useState(false)

    const recaptchaRef = useRef(null)
    const [isVerified, setIsverified] = useState(false)

    const { client } = useContext(ClientContext);

    async function onSubmit(data) {
        const { firstname, lastname, phone, email, password } = data
        setLoading(true)
        setlogErr(false)
        setIsverified(false)
        setlogErrAccount(false)
        try {
            const response = await fetch(`${API_URL}/api/clients`, POSTRequest({ 
                    firstname:firstname, 
                    lastname:lastname, 
                    email:email, 
                    phone:phone, 
                    password:password,
                    files: client.files ? client.files : '',
            }))
            if(response.status !== 200) {setlogErrAccount(true); setLoading(false);return}
            const JSONRes = await response.json()
            if(JSONRes){
                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: JSONRes.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: JSONRes.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:`http://localhost:3000${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) {
            setLoading(false)
            setlogErr(true)
            console.error('Request failed:' + err.message)
        }
    }

    const onReCAPTCHAChange = async (captchaCode) => {
        // reCAPTCHA code null / undefined indicating that it was expired then return early
        if (!captchaCode) return;
        try {
          const response = await fetch("/api/serverActions", {
            method: "POST",
            body: JSON.stringify({captcha: captchaCode }),
            headers: {
              "Content-Type": "application/json",
            },
          });
          if (response.ok) {
            setIsverified(true)
          } else {
            const error = await response.json();
            setIsverified(false)
            throw new Error(error.message)
          }
        } catch (error) {
          console.log(error?.message || "Something went wrong");
        }
      };

    return (
        <>
        {logErr ? <div className="text-sm text-[#d32f2f] text-center mb-5 scroll-mt-28" id="errorSignUp">Problème avec la séance (réservée, tuteur indisponible...)</div> : ''}
        {logErrAccount ? <div className="text-sm text-[#d32f2f] text-center mb-5 scroll-mt-28" id="errorSignUp">Compte existant (veuillez vous connecter ci-dessus)</div> : ''}
        {loading 
            ? <Loading />
            : <form onSubmit={handleSubmit(onSubmit)} className='w-full grid grid-cols-2 gap-5 relative place-self-center sm:flex sm:flex-col ' id="signUp">
                <InterfaceTextInput label='Email *' placeholder='Votre email' name="email" options={{...register("email")}} commonError={errors.email} commonErrorMessage={errors.email?.message} style='col-span-2'/>
                <InterfaceTextInput label='Nom *' placeholder='Votre nom' name="lastname" options={{...register("lastname")}} commonError={errors.lastname} commonErrorMessage={errors.lastname?.message}/>
                <InterfaceTextInput label='Prénom *' placeholder='Votre prénom' name="firstname" options={{...register("firstname")}} commonError={errors.firstname} commonErrorMessage={errors.firstname?.message}/>
                <InterfaceTextInput type='password' label='Mot de passe *' placeholder='Créer votre mot de passe' name="password" options={{...register("password")}} commonError={errors.password} commonErrorMessage={errors.password?.message}/>
                <InterfaceTextInput type='password' label='Confirmation de mot de passe *' name="confirmPassword" options={{...register("confirmPassword")}} commonError={errors.confirmPassword} commonErrorMessage={errors.confirmPassword?.message}/>
                <p className="col-span-2 my-6">En créant votre compte, vous déclarez avoir pris connaissance des <Link href='/cgv' target="_blank" className="font-bold underline underline-offset-2">conditions générales de vente</Link> et les accepter. *</p>
                <div className="flex justify-between items-center col-span-2 sm:flex-col sm:gap-6">
                    <div>
                        <ReCAPTCHA
                            sitekey={SITE_KEY}
                            ref={recaptchaRef}
                            onChange={onReCAPTCHAChange}
                        />
                    </div>
                    <button className='px-[25px] flex gap-3 rounded-xl py-5 bg-[#2A3955]' type='submit' disabled={!isVerified} style={isVerified ? {backgroundColor:'#2A3955'} : {backgroundColor:'rgb(156 163 175'}}>
                        <Image src={white_arrow} alt="Arrow icon" priority />
                        <p className='font-bold'>{`S'inscrire et payer`}</p>
                    </button>
                </div>
            </form>
        }
        </>
    )

}