module Lit.TodoMVC.App

open Browser.WebStorage
open Fable.Core.JsInterop
open Lit

// importAll "@shoelace-style/shoelace/dist/themes/light.css?inline"
importDefault "@shoelace-style/shoelace/dist/components/button/button.js"
importDefault "@shoelace-style/shoelace/dist/components/icon/icon.js"
importDefault "@shoelace-style/shoelace/dist/components/input/input.js"
importDefault "@shoelace-style/shoelace/dist/components/card/card.js"
importDefault "@shoelace-style/shoelace/dist/components/checkbox/checkbox.js"
import "setBasePath" "@shoelace-style/shoelace/dist/utilities/base-path.js"

// [<Emit("setBasePath($0)")>]
// let setBasePath (_: string): unit = jsNative
// setBasePath "/dex/static/shoelace/dist"

[<LitElement("login-app")>]
let MyApp() =
    let _ = LitElement.init(fun cfg ->
        cfg.useShadowDom <- true
    )

    let uid, setUid = Hook.useState ""
    let amnesia, setAmnesia = Hook.useState false

    let splitUid (x: string) =
      let s = x.Split '@'
      if s.Length = 1 then
        x, "default"
      else
        x, s[1]

    let getTenanatAnchor tenant  =
      let e = Browser.Dom.document.getElementById tenant
      if isNull e then
        Browser.Dom.document.getElementById "default"
      else
        e

    let gotoIdentityProvider _ =
      let uid' =
        if uid = "" then
          localStorage["user_id"]
        else uid
      let user, tenant = splitUid uid'
      let a = getTenanatAnchor tenant
      let href = a.attributes[0]
      let hint =
        if href.value.Contains "?" then
          "&login_hint"
        else
          "?login_hint"
      href.value <- $"{href.value}{hint}={user}"
      if not amnesia then
         localStorage["user_id"] <- user
      a.click()

    let onEnter e =
      let key = e?key
      if key = "Enter" then
         gotoIdentityProvider ()

    let defaultUser =
      if isNullOrUndefined localStorage["user_id"] then
         ""
      else
         localStorage["user_id"]  
      // Browser.Dom.document.cookie
      // |> fun s -> s.Split ';'
      // |> Array.filter (fun s -> s.StartsWith "user_id=")
      // |> Array.tryHead
      // |> Option.map (fun s -> s.Split '=' |> Array.last)
      // |> Option.defaultValue ""

    let toggleAmnesia _ = setAmnesia (not amnesia)
      
    html $"""
        <div class="centering">
        <div @keydown={Ev(onEnter)}>
        <sl-card class="card-overview" >
          <div style="padding: 10px; width: 300px; height: 300px">
          <img
            slot="image"
            src="/dex/static/img/ob.png"
            width="290px"
            alt="Oceanbox login"
          />
          </div>
          <sl-input placeholder="Username or email" label="User" value="{defaultUser}" clearable @sl-input={EvVal(setUid)}></sl-input>
          <div style="width: 150px; height: 50px; padding-top: 10px;">
            <sl-checkbox ?checked={not amnesia} @sl-input={Ev(toggleAmnesia)}>Remember me</sl-checkbox>
          </div>
          <div style="width: 150px; height: 50px;">
            <sl-button variant="primary" pill @click={Ev(gotoIdentityProvider)}>Next</sl-button>
          </div>
        </sl-card>
        </div>
        </div>

        <style>
          .card-overview {{
            max-width: 400px;
          }}

          .card-overview small {{
            color: var(--sl-color-neutral-500);
          }}

          .card-overview [slot='footer'] {{
            display: flex;
            justify-content: space-between;
            align-items: center;
          }}

          .centering {{
            height: 50%%;
            display: flex;
            align-items: center;
            justify-content: center;
          }}

          .centering div {{
            width: 100px;
            height: 100px;
          }}
        </style>
    """
