import * as React from 'react'

import type { TalkNPCs, TalkNPC } from '@lastres/talk-npc'
import OutputPacketTalk from '@lastres/output-packet/talk'

export interface TalkNPCsComponentProps {
    talkNPCs: TalkNPCs | null
    websocket: WebSocket | null
}
export default function TalkNPCsComponent (props: TalkNPCsComponentProps): JSX.Element {
    const npcs = props.talkNPCs
    function onWordlesslyTalk (npc: TalkNPC): void {
        if (props.websocket === null) {
            return
        }
        new OutputPacketTalk(npc.identifier).send(props.websocket)
    }
    function printAvatar (npc: TalkNPC): JSX.Element {
        if (npc.icon === undefined) {
            return <></>
        }
        return <div className="avatar">
            <img src={npc.icon}/><div className="shadow"/>
        </div>
    }
    if (npcs === null) {
        return <></>
    }
    if (Object.keys(npcs).length < 1) {
        return <>
            <p>No hay nadie para hablar ahora.</p>
        </>
    }
    return (
        <>
            <p>Disponible para hablar:</p>
            {
                Object.keys(npcs).map((identifier) => {
                    const npc = npcs[identifier]
                    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>Decir palabra</button>
                            </div>
                        </div>
                    </div>
                })
            }
        </>
    )
}
