import Image from "next/image"
import inbox from '../../../public/assets/dashboardTutors/inbox.svg'
import icon from '../../../public/assets/dashboardTutors/iconMessage.svg'
import PJ from '../../../public/assets/dashboardTutors/PJ.svg'
import icon2 from '../../../public/assets/dashboardTutors/iconConv.svg'
import background from '../../../public/assets/homepage/background.svg'
import { TutorMenu } from "@/components/menus/tutorMenu"
import { H1Title } from "@/components/littleComponents"
import { GETRequest, GETTokenRequest, POSTRequest } from "@/utils/requestHeader"
import { CircularProgress, ThemeProvider } from "@mui/material"
import { colorTheme } from "@/components/styles/mui"
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form'
import send from '../../../public/assets/dashboardTutors/send.svg'
import { object, string } from "yup";
import { toHoursAndMinutesH } from "@/utils/timeToHours"
import { useEffect, useRef, useState } from "react"

import { DashboardTitle } from '@/components/titleDashboard'
import sendPix from '../../../public/assets/dashboard/whitePicto/send.svg'
import bgClient from '../../../public/assets/dashboard/bgClient.svg'
import { NoIndexHead } from "@/utils/customHead"

export const mailbox = object({
    message:string(),
}).required();

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_tok = 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_tok.status !== 200) {
      return { 
        redirect: {
          destination: '/tuteur/',
          permanent: false,
        },
    }}
    const user = await response_tok.json()
    const queryResponse = await fetch(`${API_URL}/api/conversations/messages/client/${query.client_id}`, GETTokenRequest(authToken))
    const client = await queryResponse.json()

    const response = await fetch(`${API_URL}/api/conversations/me`, GETTokenRequest(authToken))   
    const conversations = await response.json()

    return {
      props: {
        tutorId: user.id,
        convs: conversations,
        query: client,
        client_id:query.client_id === undefined ? null : query.client_id
      }
    }
  }


export default function TutorMessagerie({convs, query, client_id, tutorId}) {
    const { v4: uuidv4 } = require('uuid');
    const [loading, setLoading] = useState(false)
    const [clientId, setClientId] = useState()
    const [threadId, setThreadId] = useState(undefined)
    const [name, setName] = useState(undefined)
    const [thread, setThread] = useState()
    const [conversations, setConversations] = useState(convs.filter(c => c.others.length > 0).sort((a, b) => (new Date(b.messages[0]?.created_at).getTime()) - new Date(a.messages[0]?.created_at).getTime()))
    const [newMsgText, setNewMsgText] = useState('Aucune conversation ouverte.')
    const threadContainer = useRef(null)
    const [docId, setDocId] = useState([])
    const [submitLoading, setSubmitLoading] = useState(false)
    const [targetFile, setTargetFile] = useState()
    const [currentType, setCurrentType] = useState()
    const [active, setActive] = useState(true)

    const {handleSubmit, register, reset} = useForm({resolver: yupResolver(mailbox)})
    
    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, 'Pièce jointe')
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [targetFile, currentType])

    useEffect(() => {
        threadContainer?.current?.scrollIntoView(false);
    }, [thread]);

    async function first_conv () {
        const res = await fetch(`${API_URL}/api/clients/${client_id}`, GETRequest).then(r => r.json())
        setName(res.firstname.charAt(0)+res.firstname.slice(1).toLowerCase())
        setNewMsgText('Envoyer un premier message...')
    }

    // ON START, FIRST QUERY
    useEffect(() => {
        if(!client_id) {
            if(conversations.length > 0) {
                setActive(conversations[0].is_active)
                setName(conversations[0].others[0].firstname.charAt(0)+conversations[0].others[0].firstname.slice(1).toLowerCase())
                const currentMessage = conversations[0].messages.slice(0).reverse().map(element => {return element});
                setClientId(conversations[0].others[0].pivot.conversationnable_id)
                setThread(currentMessage)
            }
            return
        }
        setClientId(client_id)
        if(query.message){
            first_conv()
            return
        }
        setName(query?.others[0]?.firstname.charAt(0)+query?.others[0]?.firstname.slice(1).toLowerCase())
        if(query?.messages?.length === 0) setNewMsgText('Envoyer un premier message...')
        if(query?.messages?.length>0) {
            setThreadId(query.others[0].pivot.conversation_id)
            setNewMsgText('Aucune conversation ouverte.')
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    },[query, client_id])

    // ONCLICK ON CONVERSATION
    async function currentThread (id) {
        if(!threadId || !clientId) return
        setLoading(true)
        try {
            const res = await fetch(`/api/proxy/conversations/messages/client/${id}`, GETRequest)     
            const newThread = await res.json()
            setActive(newThread.is_active)
            setThread(newThread.messages.reverse())
            setName(newThread.others[0].firstname.charAt(0)+newThread.others[0].firstname.slice(1).toLowerCase())
            setLoading(false)
        } catch (err) {
            setLoading(false)
            console.error('Request failed:' + err)
        }
    } 
    
    useEffect(() => {
        currentThread(clientId)
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [clientId, threadId])

    // SEND MESSAGE
    async function onSubmit(data) {
        if(data.message === undefined && docId?.length === 0 || data.message === '' && docId?.length === 0 || !clientId) {reset();setDocId([]);return}
        setLoading(true)
        setNewMsgText('Aucune conversation ouverte.')
        let newObj = {}
        for(let file of docId) {
            newObj[file.id] = {title: file.title}
        }
        try {
            const response = await fetch(`/api/proxy/conversations/send/client/${clientId}`, POSTRequest({text:data.message, files:newObj}))
            const responseJSON = await response.json()
            setThreadId(responseJSON.id)
            currentThread(clientId)
            reset()
            const updateConv = await fetch(`/api/proxy/conversations/me`, GETRequest) 
            const updateJSON = await updateConv.json()
            console.log(updateJSON);
            setConversations(updateJSON.filter(c => c.others.length > 0).sort((a, b) => (new Date(b.messages[0]?.created_at).getTime()) - new Date(a.messages[0]?.created_at).getTime()))
            newObj = {}
            setDocId([])
      } catch (err) {
            setLoading(false)
            console.error('Request failed:' + err.message)
      }
    }

    // console.log(clientId, threadId);
    // console.log(conversations);
    return (
        <>
        <NoIndexHead />
        <main className='w-[100vw] h-[100vh] bg-cover bg-center flex'>
            <TutorMenu id={tutorId} />
            <section className='w-full flex flex-col h-[100vh] justify-start py-28 px-20 ml-[320px]'>
                <Image src={bgClient} alt="Big pictogram" className='absolute -z-10 bottom-0 right-0'/>
                <DashboardTitle text='Messagerie' image={sendPix}/>
                <section className="w-full flex-1 max-h-full grid grid-cols-[1fr_3fr] bg-white py-8 px-10 shadow-dashboard rounded-xl">
                    <section className="flex flex-col relative h-full border-r-2 border-[#e5e7eb]">
                        <div className="flex gap-2.5 border-b-2 border-[#e5e7eb] min-h-[50px] font-semibold items-center">
                            <Image src={inbox} alt="Boite de réception" className="w-6 h-auto mb-[2px]" priority />
                            <h2>Messages</h2>
                        </div>
                        <div className="h-full w-full flex relative">
                        {conversations?.length > 0
                            ? <div className="flex flex-col max-h-full overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 absolute top-0 right-0 bottom-0 left-0">
                                {conversations && conversations?.filter(c => c.clients?.length !== 0)
                                    ? conversations?.filter(c => c.clients?.length !== 0).map(c =>
                                        <Message key={uuidv4()} image={icon2} data={c} setThreadId={setThreadId} setClientId={setClientId} />)
                                : ''
                                }
                            </div>
                            : <p className="mt-5">Aucune conversation</p>
                        }
                        </div>
                    </section>
                    <section className="flex flex-col">
                        <h2 className="border-b-2 border-[#e5e7eb] min-h-[50px] font-semibold flex items-center pl-10">{name ? name : '-'}</h2>
                        <div className="flex flex-col justify-end pl-10 h-full relative mt-5">
                            <div className="flex flex-col max-h-full gap-5 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 absolute top-0 right-0 bottom-20 left-10 pr-5">
                            {loading 
                                ? <CircularProgress size="1.5rem"/>
                                : thread
                                    ? 
                                    <>
                                        {thread?.map(t => 
                                        <Conversation   key={t.id} image={icon}
                                                        name={t.sender.firstname.charAt(0)+t.sender.firstname.slice(1).toLowerCase()} 
                                                        hour={`${new Date(t.created_at).getDate()}/${new Date(t.created_at).getMonth()+1} à ${toHoursAndMinutesH(new Date(t.created_at).getHours()*60 + new Date(t.created_at).getMinutes())}`}
                                                        message={t.text} pj={t.files} />)}
                                        <div ref={threadContainer} className="h-1 w-1 bg-transparent"></div>
                                    </>    
                                    : `${newMsgText}`
                            }
                            </div>
                            <form onSubmit={handleSubmit(onSubmit)}
                                className="w-full bg-white px-4 flex justify-between items-center gap-5">
                                <div className='flex relative items-center gap-3' style={ active ? {} : {cursor:'default',  pointerEvents: "none"}}>
                                    {submitLoading 
                                        ? <div className='flex absolute items-center justify-center w-full bg-white h-full'>
                                            <ThemeProvider theme={colorTheme}>
                                                <CircularProgress size="1.5rem" color='secondary'/>
                                            </ThemeProvider>
                                          </div>
                                        : ''
                                    }
                                    <input type="file" name='Pièce jointe' id='Pièce jointe' hidden onClick={(e) => {e.target.value = ''}} onChange={(e) => {setTargetFile(e); setCurrentType('Pièce jointe')}}/>
                                    <label htmlFor='Pièce jointe' className='bg-[#3D9EC2]/70 group hover:bg-[#3D9EC2] transition-all duration-300 cursor-pointer rounded-[5px] w-9 h-9 p-1.5 flex items-center justify-center' style={ active ? {} : {backgroundColor:'rgb(243 244 246)'}}>
                                        {docId.filter(doc => doc.title === 'Pièce jointe').length > 0
                                            ? <div className="font-medium text-lg text-white">{docId.filter(doc => doc.title === 'Pièce jointe').length}</div>
                                            : <Image src={PJ} alt="Attachment" className="w-full h-auto group-hover:scale-[1.08] transition-all duration-300" priority />
                                        }
                                    </label>
                                </div>
                                <div className="border border-[#3D9EC2] rounded-[10px] flex w-full px-4"
                                     style={ active ? {} : {backgroundColor:'rgb(243 244 246)', color:'rgb(156 163 175)', cursor:'default',  pointerEvents: "none"}}>
                                    <input autoComplete="off" className="w-full pr-2 rounded-lg h-10 font-medium focus-visible:outline-none" 
                                           style={ active ? {} : {backgroundColor:'rgb(243 244 246)', color:'rgb(156 163 175)', cursor:'default',  pointerEvents: "none"}}
                                            type="text" placeholder="Votre message..."
                                            {...register("message")}/>
                                    <button type='submit' className="w-6 h-auto">
                                        <Image src={send} alt="Envoyer" className="w-6 h-auto hover:translate-x-1 transition-all duration-300" priority />
                                    </button>
                                </div>
                            </form>
                            <div className="px-4 text-sm mt-2 text-gray-400">{`Chaque pièce jointe doit être accompagnée d'un message`}</div>
                        </div>
                    </section>
                </section>
            </section>
        </main>
        </>
        )
    }


function Conversation({image, hour, name, message, pj}) {
    const { v4: uuidv4 } = require('uuid');
    return (
        <div className="flex gap-5">
            <Image src={image} alt="Photo de profil" className="max-h-16 w-auto" priority />
            <div className="flex flex-col">
                <div className="flex gap-2 items-center">
                    <h2 className="text-lg font-semibold">{name}</h2>
                    <p className="text-xs text-black/60 mt-3">{hour}</p>
                </div>
                <p className="text-sm">{message}</p>
                {
                    pj?.length > 0 
                    ? pj?.map((doc) =>
                        <div key={uuidv4()} className='flex items-center justify-between py-2'>
                            <a href={doc?.download_url} download='Pièce jointe Scriptor' className='py-1.5 px-3 text-sm 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>
        </div>
    )
}

export function Message({image, data, setThreadId, setClientId}) {
    return (
        <div className="flex flex-col pb-5 pt-2 px-5 border-b bg-white cursor-pointer hover:bg-gray-50 transition-all duration-300" onClick={() => {setThreadId(data.id); setClientId(data.others[0]?.pivot.conversationnable_id)}}>
            <div className="flex gap-5 items-center">
                <Image src={image} alt="Photo de profil" className="max-h-20 w-auto" priority />
                <div className="flex flex-col">
                    <h2 className="text-lg font-semibold">{data?.others.length > 0 ? data?.others[0]?.firstname.charAt(0)+data?.others[0]?.firstname.slice(1).toLowerCase() : 'NoName'}</h2>
                </div>
            </div>
            <p className="text-xs text-black/60">{data?.messages[0]?.created_at ? `Dernier message le ${new Date(data?.messages[0]?.created_at).toLocaleDateString('fr')} à ${toHoursAndMinutesH(new Date(data?.messages[0]?.created_at).getHours()*60-60 + new Date(data?.messages[0]?.created_at).getMinutes())}` : "Aucun message"}</p>
        </div>
    )
}