import Image from 'next/image'
import meet from '../../../../public/assets/dashboardTutors/meet.svg'
import { GETRequest } from '@/utils/requestHeader'
import { H1Title, Back } from '@/components/littleComponents'
import { toHoursAndMinutesH } from '@/utils/timeToHours'
import { ClientMenu } from '@/components/menus/clientMenu';
import Link from 'next/link'

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 ClientBurgerMenu from '@/components/menus/clientBugerMenu'
import { lock, unlock } from '@/utils/lockScreen'
import { useState } from 'react'
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/clients`, {
    method:'GET',
    mode: "cors",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
    }
  })
  const responseJSON = await response.json()
  
  if(response.status !== 200) {
    return { 
      redirect: {
        destination: '/client/',
        permanent: false,
      },
  }}

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

export default function ClientFormationPage({order, clientId}) {
  const { v4: uuidv4 } = require('uuid');
  const [menu, setMenu] = useState(false)
  const [hamburger, setHamburger] = useState(false)

  return (
    <>
    <NoIndexHead />
    <main className='w-[100vw] bg-cover bg-center flex'>
            <ClientMenu id={clientId}/>
            <ClientBurgerMenu 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='/client/clientFormations' />
                <Link href={{ pathname: '/client/mailbox', query: {tutor_id: order.tutor_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 tuteur</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 tuteur et données renseigné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.tutor === null || order.tutor === undefined ? '-' : order.tutor.firstname.charAt(0)+order.tutor.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 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 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 col-span-2 rounded-xl shadow-dashboard 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>
                  <div className='rounded-xl overflow-hidden'>
                    <div className='grid grid-cols-5 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>
                    {
                      order.seances.map((seance, index) =>
                        <EachSeance key={index} seance={seance} index={index} order={order} />
                      )
                    }
                  </div>
                  {order.formation.sessions_number === order.seances.length 
                    ? ''
                    : <p className='place-self-center mt-10 -mb-3 font-medium w-[75%] text-center'>Les séances seront programmées par votre tuteur à la fin de votre prochaine séance, selon vos disponibilités communes.</p>
                  } 
                </section>
              </div>
            </section>
    </main>
    </>
  )
}

function EachSeance ({seance, index, order}) {
  return(
    <div style={seance.isValidate ? {backgroundColor:'rgba(34,197,94,0.2)'} : {}}>
      <div key={seance.id} className='grid grid-cols-5 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'
          style={order.seances.length === index+1 ? {border:'none'} : {}}>
        {/*for isCheck color rgba(34 197 94 / 0.4); */}
        <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.slice(0,-9)).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 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>
    </div>
  )
}
