import Image from 'next/image'
import meet from '../../../../public/assets/dashboardTutors/meet.svg'
import validate from '../../../../public/assets/dashboardTutors/validate.svg'
import add from '../../../../public/assets/gestion/add.svg';
import { GETRequest, POSTRequest } from '@/utils/requestHeader'
import {  Back } from '@/components/littleComponents'
import { Loading } from '@/components/loader'
import { useState } from 'react'
import { toHoursAndMinutesH } from '@/utils/timeToHours'
import { TutorMenu } from '@/components/menus/tutorMenu'
import Link from 'next/link'
import { AddSeance } from '@/components/dasboardTutors/addSeance';
import { lock, unlock } from '@/utils/lockScreen';
import deleteList from '../../../../public/assets/tuteur/deleteList.svg'
import { DeleteCardSeance } from '@/components/deleteCardSeance';
import { SeanceCard } from '@/components/seanceCard';

import { DashboardTitle } from '@/components/titleDashboard'
import formationPix from '../../../../public/assets/dashboard/whitePicto/formation.svg'
import bgClient from '../../../../public/assets/dashboard/bgClient.svg'

import { BlackHamburger } from '@/components/menus/clientBugerMenu'
import TuteurBurgerMenu from '@/components/menus/tuteurBurgerMenu'
import { NoIndexHead } from '@/utils/customHead';

const API_URL = process.env.NEXT_PUBLIC_API_URL

export async function getServerSideProps ({req, res, query}) {
  const Cookies = require('cookies')
  const cookies = new Cookies(req, res)
  const authToken = cookies.get('auth-token') || ''

  const response = await fetch(`${API_URL}/api/auth/me/tutors`, {
    method:'GET',
    mode: "cors",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
    }
  })
  
  if(response.status !== 200) {
    return { 
      redirect: {
        destination: '/tuteur',
        permanent: false,
      },
  }}
  const user = await response.json()

  const current_order = await fetch(`${API_URL}/api/orders/${query.order}`, GETRequest).then(r => r.json())

  return {
      props: {
        order:current_order,
        tutorId:user.id
      }
  }
}

export default function TutorFormationPage({order, tutorId}) {
  const { v4: uuidv4 } = require('uuid');
  const [loading, setLoading] = useState(false)
  const [addTime, setAddTime] = useState(false)
  const [position, setPosition] = useState(0)
  const [error, setError] = useState(false)
  const [deleteCard, setDeleteCard] = useState(false)
  const [seanceCard, setSeanceCard] = useState(false)

  const [menu, setMenu] = useState(false)
  const [hamburger, setHamburger] = useState(false)

  const [seanceId, setSeanceId] = useState(undefined)
  const [seanceMeet, setSeanceMeet] = useState(undefined)
  const [seanceCheck, setSeanceCheck] = useState(undefined)

  const isValidateMethod = (current_seance) => {
    //current date should be superior to seance date if you want to validate
    if(new Date(current_seance.beginning_date).getTime() > new Date().getTime()) return
    if(!current_seance.isValidate) { setSeanceCard(true); lock(); window?.scrollTo({top:0}); return }
    return
  }

  return (
    <>
    <NoIndexHead />
    <main className='w-[100vw] bg-cover bg-center flex'>
            <AddSeance addTime={addTime} setAddTime={setAddTime} order={order} position={position}/>
            <TutorMenu id={tutorId} />
            <TuteurBurgerMenu menu={menu} setMenu={setMenu} setHamburger={setHamburger}/>
            <section className='w-rightSide flex flex-col min-h-[100vh] px-20 py-28 ml-[320px] lg:ml-0 xl:px-5 xl:py-10 lg:w-[95vw]'>
              <Image src={bgClient} alt="Big pictogram" className='absolute -z-10 bottom-0 right-0'/>
              <DashboardTitle text='Formation' image={formationPix}/>
              <div onClick={() => {setMenu(!menu); menu ? unlock() : lock()}} className='hidden z-40 absolute top-7 left-8 lg:block'>
                <BlackHamburger hamburger={hamburger} setHamburger={setHamburger}/>
              </div>
              <div className='flex justify-between mt-20'>
                <Back title="Retour à la liste" linkTo='/tuteur/tutorFormations' />
                <Link href={{ pathname: '/tuteur/mailbox', query: {client_id: order.client_id}}} className='rounded flex items-center cursor-pointer z-10 text-white px-5 mb-5 text-sm bg-[#3D9EC2]/70 hover:bg-[#3D9EC2] transition-all duration-300 lg:hidden'>
                  <button>Envoyer un message au client</button>
                </Link>
              </div>
              <div className='gap-5 grid-cols-2 grid lg:flex lg:flex-col lg:gap-10 lg:items-center'>
                <section className='w-full bg-white rounded-xl shadow-dashboard place-self-start py-10 px-14 flex flex-col xl:px-6 xl:py-5 xl:max-w-[650px] lg:place-self-auto'>
                  <h2 className="text-xl text-[#3D9EC2]/70 mb-5 self-center xl::text-lg">Informations client et autres données</h2>
                  <div className='flex flex-col gap-2 text-lg xl:text-base'>
                  { order.tutor 
                    ? <div className='flex flex-col gap-1.5 pb-5 border-b border-gray-300'>
                      <p className='text-gray-600'>Prénom : <span className='font-medium text-typo'>{`${order.client.firstname.charAt(0)+order.client.firstname.slice(1).toLowerCase()}`}</span></p>
                    </div>
                      :''
                    }
                    <div className='flex flex-col gap-1.5 pt-4 pb-5 border-b border-gray-300'>
                      {order.study_level === null || order.study_level === undefined ? '' : <p className='text-gray-600'>{`Niveau d'étude : `}<span className='font-medium text-typo'>{order.study_level}</span></p>}
                      {order.study_title === null || order.study_title === undefined ? '' : <p className='text-gray-600'>Formation suivie / Diplôme visé : <span className='font-medium text-typo'>{order.study_title}</span></p>}
                      {order.delay === null || order.delay === undefined ? '' : <p className='text-gray-600'>Délai de réalisation : <span className='font-medium text-typo'>{order.delay}</span></p>}
                      {order.timing === null || order.timing === undefined ? '' : <p className='text-gray-600'>Session choisie : <span className='font-medium text-typo'>{order.timing}</span></p>}
                    </div>
                    <div className='flex gap-2 flex-col pt-4'>
                      <p className='text-gray-600'>Document(s)</p>
                      <div className='flex gap-x-3 flex-wrap'>
                        {
                            order?.files?.length > 0 ?
                            order?.files?.map((doc) =>
                                <div key={uuidv4()} className='flex items-center justify-between py-2'>
                                  <a href={doc?.download_url} download className='p-1 bg-[#3D9EC2]/10 rounded-lg max-w-[300px] overflow-hidden text-ellipsis whitespace-nowrap hover:bg-[#3D9EC2]/20 transition-all duration-300  hover:max-w-none'>{doc.pivot.title}</a>
                              </div>
                              )
                            : <div className='font-medium text-typo'>Aucun document</div>
                        }
                      </div>
                    </div>
                  </div>
                </section>
                <section className='w-full bg-white shadow-dashboard rounded-xl place-self-start py-10 px-14 flex flex-col xl:px-6 xl:py-5 xl:max-w-[650px] lg:place-self-auto'>
                  <h2 className="text-xl text-[#3D9EC2]/70 mb-5 self-center xl:text-lg">Informations sur la formation</h2>
                  <div className='flex flex-col gap-2 text-lg xl:text-base'>
                    <div className='flex flex-col gap-1.5 pb-5 border-b border-gray-300'>
                      <p className='text-gray-600'>Expertise : <span className='font-medium text-typo'>{order.formation.expertises}</span></p>
                      <p className='text-gray-600'>Discipline : <span className='font-medium text-typo'>{order.discipline}</span></p>
                      <p className='text-gray-600'>Service : <span className='font-medium text-typo'>{order.formation.services}</span></p>
                    </div>
                    <div className='flex flex-col gap-1.5 pt-4'>
                      <p className='text-gray-600'>Nombre de séances : <span className='font-medium text-typo'>{order.formation.sessions_number}</span></p>
                      <p className='text-gray-600'>Durée par séance : <span className='font-medium text-typo'>{toHoursAndMinutesH(order.formation.session_duration)}</span></p>
                      <p className='text-gray-600'>Durée totale : <span className='font-medium text-typo'>{toHoursAndMinutesH(order.formation.session_duration * order.formation.sessions_number)}</span></p>
                    </div>
                  </div>
                </section>
                <section className='w-full bg-white shadow-dashboard col-span-2 rounded-xl place-self-start p-10 gap-5 flex flex-col text-lg xl:text-base xl:px-6 xl:py-5 lg:col-span-1 lg:max-w-[650px] lg:place-self-auto'>
                  <h2 className="text-xl text-[#3D9EC2]/70 self-center xl:text-lg">Renseignements supplémentaires</h2>
                  {order.problematic === null || order.problematic === undefined ? '' : <p className='text-gray-600'>Problématique : <span className='font-medium text-typo'>{order.problematic}</span></p>}
                  {order.search_hypothesis === null || order.search_hypothesis === undefined ? '' : <p className='text-gray-600'>Hypothèse(s) de recherche : <span className='font-medium text-typo'>{order.search_hypothesis === 1 ? 'Oui' : 'Non'}</span></p>}
                  {order.questionnaire === null || order.questionnaire === undefined ? '' : <p className='text-gray-600'>Nombre de questionnaire(s) à analyser : <span className='font-medium text-typo'>{order.questionnaire}</span></p>}
                  {order.pages === null || order.pages === undefined ? '' : <p className='text-gray-600'>Nombre de page(s) : <span className='font-medium text-typo'>{order.pages}</span></p>}
                  {order.word_number === null || order.word_number === undefined ? '' : <p className='text-gray-600'>Nombre de mot(s) : <span className='font-medium text-typo'>{order.word_number}</span></p>}
                  {order.presentation_duration  === null || order.presentation_duration  === undefined ? '' : <p className='text-gray-600'>{`Durée de l'exposé oral  : `}<span className='font-medium text-typo'>{order.presentation_duration }</span></p>}
                  {order.statut  === null || order.statut  === undefined ? '' : <p className='text-gray-600'>{`Statut visé : `}<span className='font-medium text-typo'>{order.statut }</span></p>}
                  {order.subject_description === null || order.subject_description === undefined ? '' : 
                    <div>
                      <p className='font-medium mb-1'>Description : </p>
                      <p className=' text-typo'>{`${order.subject_description}`}</p>
                    </div>
                  }
                  <div>
                    <p className='font-medium mb-1'>Commentaire additionnel : </p>
                    <p className=' text-typo'>{order.comment ? `${order.comment}` : 'Aucun commentaire'}</p>
                  </div>
                </section>
                <section className='flex flex-col shadow-dashboard bg-white col-span-2 w-full rounded-xl pt-10 pb-14 px-14 xl:px-5 xl:py-5 lg:max-w-[650px]'>
                  <h2 className="text-xl text-[#3D9EC2]/70 mb-10 place-self-center xl:text-lg xl:mb-5">Séances</h2>
                  {error ? <div className='place-self-center -mt-5 mb-4 text-red-500'>{`Une erreur est survenue`}</div>: ''}
                  <div className='rounded-xl overflow-hidden'>
                    <div className='grid grid-cols-[repeat(5,2fr)_1fr] p-5 bg-gray-100 text-gray-400 border-b border-gray-300 items-center justify-items-center px-5 sm:grid-cols-3'>
                        <p className='sm:hidden'>Numéro</p>
                        <p className='sm:hidden'>Status</p>
                        <p>Date</p>
                        <p>Heure</p>
                        <p>Meet</p>
                    </div>
                    { loading 
                        ? <Loading />
                        : order.seances.map((seance, index) =>
                          <div key={seance.id} className='grid grid-cols-[repeat(5,2fr)_1fr] p-5 border-b border-gray-300 text-typo/90 font-medium bg-[#3D9EC2]/10 justify-items-center items-center px-5 sm:grid-cols-3 2sm:text-sm sm:gap-y-5'
                              style={order.seances.length === index+1 ? {border:'none'} : {}}>
                            <p className='font-semibold sm:hidden'>{index+1}</p>
                            <p className='sm:hidden'>{seance.isValidate ? 'Validé' : 'Non effectuée'}</p>
                            <p>{new Date(seance.beginning_date).toLocaleDateString('fr')}</p>
                            <p>{seance.beginning_date.slice(11,-3)}</p>
                            <Link href={`${seance.google_meet_link}`} target='_blank' >
                              <button className='group flex gap-2 border text-sm items-center bg-[#3D9EC2]/70 hover:bg-[#3D9EC2] transition-all duration-300 rounded text-white py-1 px-2.5'>
                                <p className='sm:hidden'>Lien</p>
                                <Image src={meet} alt="meet icon" className="group-hover:scale-[1.18] transition-all duration-300 w-6 h-auto mb-[1px]" priority />
                              </button>
                            </Link>
                            <div className='flex gap-2 h-full sm:col-span-3'>
                              <button onClick={() => {isValidateMethod(seance);setSeanceId(seance.id);setSeanceCheck(!seance.isValidate)}} className='group flex border text-sm items-center bg-[#3D9EC2]/70 hover:bg-[#3D9EC2] transition-all duration-500 rounded-lg text-white w-10 h-10 justify-center' style={seance.isValidate ? {backgroundColor:'rgba(22 163 74 / 0.8)', borderRadius:'100%'} : {}}>
                                <Image src={validate} alt="meet icon" className="group-hover:scale-[1.18] transition-all duration-300 w-6 h-auto" priority />
                              </button>
                              <button onClick={() => {setSeanceId(seance.id);setSeanceMeet(seance.google_event_id);setDeleteCard(true); lock(); window?.scrollTo({top:0})}} className='group flex gap-2 border text-sm items-center bg-red-400 hover:bg-red-500 transition-all duration-300 rounded-lg text-white py-1 px-2' style={seance.isValidate ? {display:'none'} : {}}>
                                <Image src={deleteList} alt="meet icon" className="group-hover:scale-[1.18] transition-all duration-300 w-6 h-auto" priority />
                              </button>
                              <SeanceCard seanceCard={seanceCard} setSeanceCard={setSeanceCard} id={seanceId} check={seanceCheck} setError={setError} />
                              <DeleteCardSeance deleteCard={deleteCard} setDeleteCard={setDeleteCard} id={seanceId} meet={seanceMeet} setError={setError} />
                            </div>
                          </div>
                      )
                    }
                  </div>
                  <button className='group mt-10 place-self-center flex font-medium justify-center gap-2 border text-base items-center bg-[#3D9EC2]/70 hover:bg-[#3D9EC2] transition-all duration-300 rounded text-white py-3 px-4' onClick={() => {setPosition(document?.documentElement?.scrollTop);setAddTime(true); lock()}} style={order.seances.length >= order.formation.sessions_number ? {display:'none'} : {display:'flex'}}>
                    <p>Ajouter une nouvelle séance</p>
                    <Image src={add} alt="meet icon" className="group-hover:scale-[1.18] transition-all duration-300 w-6 h-auto" priority />
                  </button>
                </section>
              </div>
            </section>
    </main>
    </>
  )
}