import * as React from 'react'

import type { TalkNPC } from '@lastres/talk-npc'
import type { OnWordSelectCallback } from '@lastres/components/game'
import { StateGame } from '@lastres/components/game'

import OutputPacketTalk from '@lastres/output-packet/talk'

export interface TalkNPCComponentData {
    npc: TalkNPC
    websocket: WebSocket | null
    key: string
    setStateGame: (set: StateGame) => void
    setOnWordSelect: (set: OnWordSelectCallback) => void
}

export default function TalkNPCComponent (props: TalkNPCComponentData): JSX.Element {
    const npc = props.npc
    function onWordlesslyTalk (npc: TalkNPC): void {
        if (props.websocket === null) {
            return
        }
        new OutputPacketTalk(npc.identifier).send(props.websocket)
    }

    function onWantToSayWord (): void {
        props.setStateGame(StateGame.SelectingWord)
        props.setOnWordSelect((npc: TalkNPC, word: string) => {
            console.log(`Trying to say ${word} to `, props.npc)
        })
    }

    function printAvatar (npc: TalkNPC): JSX.Element {
        if (npc.icon === undefined) {
            return <></>
        }
        return <div className="avatar">
            <img src={npc.icon}/><div className="shadow"/>
        </div>
    }

    return <div key={npc.identifier} className="talk-npc">
        <div className="detail">
            <div className="name-container">
                {
                    printAvatar(npc)
                }
                <div className="name">
                    <p>{npc.name}</p>
                </div>
            </div>
            <div className="buttons">
                <button onClick={() => {
                    onWordlesslyTalk(npc)
                }}>Hablar</button>
                <button onClick={() => {
                    onWantToSayWord()
                }}>Decir palabra</button>
            </div>
        </div>
    </div>
}
