import { useEffect, useRef, useState } from "react";
import { Countdown } from "../comps/timer";
import { Conversation } from "./conversation";
import { Status, useChat } from "../util/useChat";


const EmojiType={
    phone: '📞',
    headphone: '🎧',
    speaker: '🔊',
    chat: '💬',
}

export function Flow(){

    const [cuelist, setCuelist] = useState([]);
    const [currentCue, setCurrentCue] = useState(null);
    const [chatWelcome, setChatWelcome] = useState(null);

    const refTimer=useRef();
    const refAudio=useRef();
    const refInput=useRef();

    const { history, status, reset, sendMessage, setStatus, audioOutput, setAudioOutput, stop:stopChat }=useChat();
    


    function playCue(cue) {

        if(!cue) return;
        console.log('Playing cue:', cue);
        setCurrentCue(cue);

        if(parseFloat(cue.id)<=4.1){
            // Special case for starting a conversation
            console.log('clear conversation...');
            reset();            
        }

        if(cue.type=='chat' && cue.id=='4.1'){ 
            // Special case for starting a conversation
            console.log('Starting conversation...');
            sendMessage();            
            setChatWelcome(true); 
        }


        if(cue.audioFile){
            // Stop any currently playing audio
            if(refAudio.current) {
                refAudio.current.pause();             
            }

            const audio = new Audio(cue.audioFile);
            
            if(cue.loop){
                audio.loop = true;
            }

            audio.play().catch(error => {
                console.error('Error playing audio:', error);
            });        

            audio.onended = () => {
                onCueEnd(cue);
            }

            refAudio.current = audio;
            audio.addEventListener("loadedmetadata", () => {
                refTimer.current.restart(audio.duration*1000 || 0);
            });
        }
        
        if(cue.duration){
            refTimer.current.restart(cue.duration*1000, ()=>{
                onCueEnd(cue);
            });
        }
    }

    function onCueEnd(cue) {

        if(!cue) return;
        console.log('onCueEnd:', cue.id);

        if(cue.type=='chat'){
            // sendChatMessage
            const message= refInput.current.value?.trim();
            if(message && message.length>0) {
                                
                sendMessage(message);
                setChatWelcome(false); 

            }else{
                // if no message, just continue to next cue
                console.log('No message to send, continuing to next cue');
                playCue(cuelist.find(c => c.id === cue.nextcue));
            }

        }else{
            if(cue.auto) {
                playCue(cuelist.find(c => c.id === cue.nextcue));
            }
        }
    }

    function onStop(){
        console.log('Stopping current cue');
        if(refAudio.current) {
            refAudio.current.pause();
            refAudio.current = null;
        }
        setCurrentCue(null);
        refTimer.current.restart(0);

        stopChat(); // Stop chat processing
    }

    useEffect(()=>{
        switch(status) {            
            case Status.SUCCESS:
                console.log('Success!');

                setStatus(Status.IDLE);
                refInput.current.value = ''

                if(chatWelcome) {
                    return;
                }


                // play next cue                
                if(currentCue.nextcue!=5 && currentCue.nextcue!=6){ // Q5 & Q6 wait for audio end
                    if(currentCue.nextcue) {
                        playCue(cuelist.find(c => c.id === currentCue.nextcue));
                    } else {
                        setCurrentCue(null);
                    }
                }
                

                break;
            case Status.AUDIO_ENDED:
                console.log('Audio ended');
                if(currentCue.nextcue==5 || currentCue.nextcue==6){ // Q5 & Q6 wait for audio end
                    playCue(cuelist.find(c => c.id === currentCue.nextcue));
                }
                break;
        }

    },[status]);


    useEffect(()=>{
        fetch('/cuelist.json')
            .then(response => response.json())
            .then(data => {
                console.log('Cuelist data:', data);
                setCuelist(data.cuelist);
            })
            .catch(error => {
                console.error('Error fetching cuelist:', error);
            });

    },[]);


    return (
        <main className="items-center">

            <div className="w-full p-2 flex flex-row justify-center gap-2 *:w-[10vw] *:h-[10vw]">
                <div className="bg-gray-100 text-4xl font-bold mb-4 flex justify-center items-center">
                    {currentCue?.name}
                </div>
                <Countdown ref={refTimer} />
                <button className="!bg-red-300" onClick={onStop}>Stop</button>
            </div>
            <div className=" max-h-[33vh] overflow-y-auto">
                <table className="border-collapse **:border-y w-full **:p-2">
                    <thead>
                        <tr className="text-left">
                            {/* <th>ID</th> */}
                            <th>Name</th>
                            <th>Description</th>
                            <th>Type</th>
                            <th>Auto</th>
                            <th>Audio / Due</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        {cuelist?.map(({id, name, description, type, auto, audioFile,...props}, index) => (
                            <tr key={id}>
                                {/* <td>{id}</td> */}
                                <td>{name}</td>
                                <td>{description}</td>
                                <td>{EmojiType[type]}</td>
                                <td>{auto ? '⤵️' : ''}</td>
                                <td>{audioFile || props.duration}</td>
                                <td>
                                    <button className="rounded-full !bg-green-200"
                                        onClick={()=>{
                                            playCue({id, name, description, type, auto, audioFile, ...props});
                                        }}>go</button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
            <div className="flex-1 w-full overflow-y-auto flex flex-col gap-2">
                 <div className="flex-1 flex flex-col overflow-y-auto gap-2">
                    {history?.map((msg, index) => (
                        <div key={index} className={`w-5/6 ${msg.role=='user'? 'self-end':''}`}>
                            <div className={`${msg.role=='user'? 'bg-green-300':'bg-pink-300'} px-2`}>{msg.content}</div>
                            {msg.prompt && <div className="text-xs bg-gray-200">{msg.prompt}</div>}
                        </div>
                    ))}
                </div>
                <textarea ref={refInput} name="message" rows={2} 
                    className={`w-full border-1 resize-none p-2 ${status!=Status.IDLE && status!=Status.AUDIO_ENDED? 'bg-gray-500':''}`}
                    disabled={status!=Status.IDLE && status!=Status.AUDIO_ENDED}></textarea>       
                <div className="flex flex-row justify-end gap-2">
                    <span className="flex flex-row gap-1">
                        <label>audio_output</label>
                        <input type='checkbox' checked={audioOutput} onChange={(e) => setAudioOutput(e.target.checked)} />
                    </span>
                    <div className="rounded-2xl bg-gray-300 self-end px-4 tracking-widest">chat_status= {status}</div>                                                                
                </div>
            </div>
        </main>
    );
}