package io.udash.web.guide.views.ext.demo.bootstrap

import io.udash.bootstrap.button.UdashButtonOptions
import io.udash.web.guide.demos.AutoDemo
import io.udash.web.guide.styles.partials.GuideStyles
import org.scalajs.dom.Element
import scalatags.JsDom.all.*

object ButtonsDemo extends AutoDemo {

  private val (rendered: Element, source: String) = {
    import io.udash.*
    import io.udash.bootstrap.*
    import io.udash.bootstrap.utils.BootstrapStyles.*
    import io.udash.bootstrap.button.UdashButton
    import io.udash.css.CssStyle
    import io.udash.css.CssView.*
    import scalatags.JsDom.all.*

    import scala.util.Random

    val disabledButtons = Property(Set.empty[Int])

    def bottomMargin: CssStyle = {
      Spacing.margin(
        side = Side.Bottom,
        size = SpacingSize.Normal
      )
    }

    val buttons: Seq[UdashButton] = Color.values.map(color =>
      UdashButton(
        options = UdashButtonOptions(
          color.opt,
          Size.Small.opt,
        ),
        disabled = disabledButtons.transform(_.contains(color.ordinal))
      )(_ => Seq[Modifier](
        color.name,
        Spacing.margin(size = SpacingSize.ExtraSmall)
      ))
    )

    val clicks = SeqProperty[String](Seq.empty)
    buttons.foreach(_.listen {
      case UdashButton.ButtonClickEvent(source, _) =>
        clicks.append(source.render.textContent)
    })

    val push = UdashButton(
      options = UdashButtonOptions(
        size = Size.Large.opt,
        block = true
      )
    )("Disable random buttons!")
    push.listen {
      case UdashButton.ButtonClickEvent(_, _) =>
        clicks.set(Seq.empty)

        val maxDisabledCount = Random.nextInt(buttons.size + 1)
        disabledButtons.set(Seq.fill(maxDisabledCount)(
          Random.nextInt(buttons.size)
        ).toSet)
    }

    div(
      div(bottomMargin)(push),
      div(
        Display.flex(),
        Flex.justifyContent(FlexContentJustification.Center),
        bottomMargin
      )(buttons),
      h4("Clicks: "),
      produce(clicks)(seq =>
        ul(Card.card, Card.body, Background.color(Color.Light))(seq.map(li(_))).render
      )
    ).render
  }.withSourceCode

  override protected def demoWithSource(): (Modifier, String) = {
    import io.udash.css.CssView.*
    (rendered.setup(_.applyTags(GuideStyles.frame)), source)
  }
}

