import logging
from dataclasses import dataclass
from typing import Any

from fasthtml import serve
from fasthtml.components import *

from myfasthtml.controls.helpers import mk
from myfasthtml.core.bindings import Binding
from myfasthtml.core.commands import Command
from myfasthtml.core.utils import debug_routes
from myfasthtml.myfastapp import create_app

logging.basicConfig(
  level=logging.DEBUG,  # Set logging level to DEBUG
  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',  # Log format
  datefmt='%Y-%m-%d %H:%M:%S',  # Timestamp format
)

app, rt = create_app(protect_routes=False)


@dataclass
class Data:
  value: Any = "Hello World"


def add_suggestion():
  nb = len(data.value)
  data.value = data.value + [f"suggestion{nb}"]


def remove_suggestion():
  if len(data.value) > 0:
    data.value = data.value[:-1]


data = Data(["suggestion0", "suggestion1", "suggestion2"])


@rt("/")
def get():
  datalist = Datalist(
    id="suggestions"
  )
  input_elt = Input(name="input_name", list="suggestions")
  label_elt = Label()
  
  mk.manage_binding(datalist, Binding(data))
  mk.manage_binding(label_elt, Binding(data))
  
  add_button = mk.button("Add", command=Command("Add", "Add a suggestion", add_suggestion).bind(data))
  remove_button = mk.button("Remove", command=Command("Remove", "Remove a suggestion", remove_suggestion).bind(data))
  
  return Div(
    add_button,
    remove_button,
    input_elt,
    datalist,
    label_elt
  )


if __name__ == "__main__":
  debug_routes(app)
  serve(port=5002)
