import { useSiteContext } from '@context/SiteContext'
import useAuth from '@hooks/useAuth'
import { NAV_ROUTES } from '@routes/routes'
import { A } from '@solidjs/router'
import { IconLogout, IconTriangle } from '@tabler/icons-solidjs'
import { For, Show } from 'solid-js'
import { Dynamic } from 'solid-js/web'
import './navbar.scss'

export default function Navbar() {
  const { store, setAuth } = useSiteContext()
  const { clickLogOut } = useAuth(setAuth)

  const logOut = async () => {
    try {
      await clickLogOut()
    } catch (error) {
      console.log({
        status: 'danger',
        title: 'Logout fail!',
        closable: false,
      })
    }
  }

  return (
    <div class="drawer-side lg:h-[calc(100svh-64px)]">
      <label for="nav-menu" aria-label="close sidebar" class="drawer-overlay" />
      <div class="bg-base-200 w-80 min-h-full">
        <Show when={store.auth}>
          <div class="flex items-center justify-between px-5 pt-5 lg:hidden">
            <div class="avatar">
              <div class="w-9 mask mask-hexagon">
                <img
                  src={`https://ui-avatars.com/api/?name=${store.userInfo?.name}`}
                  alt="avatar"
                />
              </div>
            </div>
            <span class="mx-3 line-clamp-1">
              <A href="/me">{store.userInfo?.name}</A>
            </span>
            <button class="btn btn-ghost btn-sm" onClick={logOut}>
              <IconLogout size={16} />
            </button>
          </div>
          <div class="divider divider-success mb-0 lg:hidden">
            <IconTriangle size={30} />
          </div>
        </Show>
        <ul class="scrollnavbar menu p-4 w-80 text-base-content bg-transparent py-6 px-4">
          <For each={NAV_ROUTES}>
            {(item) =>
              item.show && (
                <li class="mb-2">
                  <A href={item.path}>
                    <Dynamic component={item.icon} />
                    {item.text}
                  </A>
                </li>
              )
            }
          </For>
        </ul>
      </div>
    </div>
  )
}
