import { type ElementStyle, type DrawableStyle, type Style, type StyleFn, type AppearStyle, type DisappearStyle, Element, type TextStyle, type Color, type OnLayoutCallback, type BaseStyle, type AnimateStyle } from "./UINode";

type InputStyle = { placeholder?: string, placeholderColor?: Color, type?: "text" | "password" | "search" }
export type UIInputStyle = ElementStyle & DrawableStyle & TextStyle & InputStyle

export interface UIInput {
  readonly type: "input",

  value: string

  style: Style<this, UIInputStyle & { onFocused?: DrawableStyle & BaseStyle & { duration?: number } }>,
  animateTo: AnimateStyle<this, DrawableStyle & BaseStyle>
  animateFrom: AnimateStyle<this, DrawableStyle & BaseStyle>

  onChange(callback: (value: string) => void): UIInput
  onFocus(callback: () => void): UIInput
  onBlur(callback: () => void): UIInput
  onLayout(onLayout: OnLayoutCallback): this

  setClass(name: string, enabled: boolean): this
  toggleClass(name: string): this
  hasClass(name: string): boolean
  bindClass(name: string, fn: () => boolean): this
}

export interface UITextArea {
  readonly type: "textarea",

  value: string

  style: Style<this, UIInputStyle & { onFocused?: DrawableStyle & BaseStyle & { duration?: number } }>,
  // styleV: StyleFn<this, UIInputStyle>,
  // styleH: StyleFn<this, UIInputStyle>,

  // appear: AppearStyle<this, UIInputStyle>
  // disappear: DisappearStyle<this, UIInputStyle>

  onChange(callback: (value: string) => void): UITextArea
  onFocus(callback: () => void): UITextArea
  onBlur(callback: () => void): UITextArea

  setClass(name: string, enabled: boolean): this
  toggleClass(name: string): this
  hasClass(name: string): boolean
  bindClass(name: string, fn: () => boolean): this
}

class InputElement<T extends "input" | "textarea"> extends Element<T> {
  
  readonly cl: Function[] = []
  readonly fl: Function[] = []
  readonly bl: Function[] = []

  get value() {
    return _creatorUI.getTextValue(this._id)
  }
  set value(value: string) {
    if (this._id !== 0) {
      _creatorUI.updateNode(this._id, "value", value)
    }
  }

  onChange (callback: (value: string) => void): this {
    this.cl.push(callback)
    return this
  }
  onFocus(callback: () => void): this {
    this.fl.push(callback)
    return this
  }
  onBlur(callback: () => void): this {
    this.bl.push(callback)
    return this
  }
}

export function UIInput(): UIInput;
export function UIInput(style: UIInputStyle): UIInput;
export function UIInput(style?: UIInputStyle): UIInput {
  return new InputElement("input", style ?? {})
}

export function UITextArea(): UITextArea;
export function UITextArea(style: UIInputStyle): UITextArea;
export function UITextArea(style?: UIInputStyle): UITextArea {
  return new InputElement("textarea", style ?? {})
}

