import { getProfile } from '@api/user'
import Logo from '@assets/images/logo.svg'
import { useSiteContext } from '@context/SiteContext'
import useAuth from '@hooks/useAuth'
import useToast from '@hooks/useToast'
import { A } from '@solidjs/router'
import { IconLogout, IconMenuDeep, IconUserCircle } from '@tabler/icons-solidjs'
import { Helpers } from '@utils/helper'
import { Show, onMount } from 'solid-js'

export default function Header() {
  const { store, setAuth, setUser } = useSiteContext()
  const { clickLogOut } = useAuth(setAuth)
  const notify = useToast()

  onMount(async () => {
    try {
      const resp = await getProfile()
      if (resp.status === 200) {
        setUser(resp.data)
      }
    } catch (error) {
      notify.error({
        title: 'Get profile fail!',
        closable: false,
        description: error?.data || 'Can not get user profile!',
      })
    }
  })

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

  return (
    <header class="w-full navbar py-3 px-4 items-center justify-between bg-fu-primary">
      <div class="flex-1">
        <A href="/" class="text-white flex items-center hover:text-white">
          <img src={Logo} class="w-8" alt="Logo" />
          <span class="ml-2 text-2xl">Fuware</span>
        </A>
      </div>
      <Show when={store.auth}>
        <div class="flex-initial">
          <div class="dropdown dropdown-end hidden lg:flex">
            <div
              tabindex="0"
              role="button"
              class="btn btn-ghost btn-circle w-10 h-10 min-h-10 avatar"
            >
              <div class="w-8 rounded-full">
                <img
                  src={`https://ui-avatars.com/api/?name=${store.userInfo?.name}&background=fb9678`}
                  alt="avatar"
                />
              </div>
            </div>
            <ul
              tabindex="0"
              class="mt-12 z-[1] p-2 shadow-md menu menu-sm dropdown-content bg-base-100 rounded-box w-52"
            >
              <li class="border rounded-full mb-1">
                <span class="menu-title text-black font-bold !py-1">
                  {store.userInfo?.name}
                </span>
              </li>
              <li class="mb-1">
                <A href={Helpers.getRoutePath('profile')}>
                  <IconUserCircle size={15} />
                  Profile
                </A>
              </li>
              <li>
                <a onClick={logOut}>
                  <IconLogout size={15} />
                  Logout
                </a>
              </li>
            </ul>
          </div>
          <label
            for="nav-menu"
            class="btn btn-ghost btn-sm drawer-button pr-0 lg:hidden"
          >
            <IconMenuDeep size={25} color="white" />
          </label>
        </div>
      </Show>
    </header>
  )
}
