import React from 'react'
import { Renderer, RendererProps } from '../../../factory'
import { BaseSchema, SchemaApi } from '../../../Schema'
import { IScopedContext, ScopedContext } from '../../../Scoped'
import { ActionSchema } from '../../Action'

export interface MenuListSchema extends BaseSchema {
  type: 'menu-list'
  header?: string
  keyField: string
  labelField: string
  iconField?: string
  api?: SchemaApi
  itemAction?: ActionSchema
}

interface MenuListState {
  activeKey?: React.Key
  items: any[]
}

export interface MenuListProps extends RendererProps, Omit<MenuListSchema, 'type' | 'className'> { }

export class MenuList extends React.Component<MenuListProps, MenuListState> {

  constructor(props: MenuListProps) {
    super(props)
    const { keyField, defaultData } = props
    this.state = {
      activeKey: Array.isArray(defaultData) ? defaultData.length > 0 ? defaultData[keyField] : undefined : undefined,
      items: Array.isArray(defaultData) ? defaultData : []
    }
  }

  componentDidMount() {
    const { api, env, keyField, onAction, itemAction } = this.props
    if (api) {
      env.fetcher(api).then(res => {
        const items = res.data.items
        if (res.ok && Array.isArray(items)) {
          if (items.length > 0) {
            this.setState({ items: items, activeKey: items[0][keyField] })
            onAction(undefined, itemAction, items[0], undefined, this.context)
          }
        }
      })
    }
  }

  handleClickItem(e: React.UIEvent<any>, ctx: object) {
    const { itemAction, onAction, keyField } = this.props
    this.setState({ activeKey: ctx[keyField] })
    onAction(e, itemAction, ctx, undefined, this.context)
  }

  render() {
    const { activeKey, items } = this.state
    const { header, keyField, iconField, labelField } = this.props

    return (
      <div className={'menu-list'}>
        <div className='menu-list-header'>
          {header}
        </div>
        <div className='menu-list-body'>
          {items.map(item => (
            <div
              key={item[keyField]}
              className={`menu-list-body-item ${item[keyField] == activeKey ? 'menu-list-body-item-selected' : ''}`}
              onClick={(e) => this.handleClickItem(e, item)}
            >
              <i className={`menu-list-body-item-icon ${item[iconField ?? ''] ?? 'fa fa-folder'}`} />
              <span className='menu-list-body-item-title'>{item[labelField]}</span>
            </div>
          ))}
        </div>
      </div>
    )
  }

}

@Renderer({
  type: 'menu-list'
})
export class MenuRenderer extends MenuList {

  static contextType = ScopedContext;

  constructor(props: MenuListProps, context: IScopedContext) {
    super(props);

    const scoped = context;
    scoped.registerComponent(this);
  }

  componentWillUnmount() {
    const scoped = this.context as IScopedContext;
    scoped.unRegisterComponent(this);
  }

}