import * as React from 'react'

import type { Action, ActionHash } from '@lastres/action'
import OutputPacketExecuteAction from '@lastres/output-packet/execute_action'

import PresentationItem from '@lastres/components/presentation-item'
import Presentation from '@lastres/components/presentation'

export interface BottomPanelProps {
    websocket: WebSocket | null
    actionHash: ActionHash | null

}

export interface Style {
    background?: string
}

export default function BottomPanel (props: BottomPanelProps): JSX.Element {
    const actionHash = props.actionHash
    function printListActions(): JSX.Element {
        if (actionHash === null) {
            return <></>
        }
        const listOfActionKeys = Object.keys(actionHash).sort((a, b) => {
            const isDisabledComparisionValue: number = +actionHash[a].is_disabled - +actionHash[b].is_disabled
            if (isDisabledComparisionValue !== 0) {
                return isDisabledComparisionValue
            }
            if (actionHash[a].name < actionHash[b].name) {
                return -1
            }
            if (actionHash[a].name > actionHash[b].name) {
                return 1
            }
            return 0
        })
        function printDisabledReason (action: Action): JSX.Element {
            if (!action.is_disabled || action.disabled_reason === null) {
                return <></>
            }
            return (
                <p className="disabled-reason" style={{ color: 'red' }}>{action.disabled_reason}</p>
            )
        }
        return <>
            <p>Acciones disponibles.</p>
            {
                listOfActionKeys.map((key) => {
                    const style: Style = {}
                    const action = actionHash[key]
                    if (action.is_disabled) {
                        style.background = 'lightgray'
                    }
                    function onClick (): void {
                        if (action.is_disabled) {
                            return
                        }
                        if (props.websocket !== null) {
                            new OutputPacketExecuteAction(action.identifier)
                                .send(props.websocket)
                        }
                    }
                    return <a onClick={onClick} className="action" style={style} key={action.identifier}>
                        <p>{action.name}</p>
                        {
                            printDisabledReason(action)
                        }
                    </a>
                })
            }
        </>
    }
    return (
        <Presentation>
            <PresentationItem>
                {
                    printListActions()
                }
            </PresentationItem>
            <PresentationItem>
            </PresentationItem>
            <PresentationItem>
            </PresentationItem>
        </Presentation>
    )
}
