import { getProfile } from '@api/user'
import fuwareLogo from '@assets/logo-fuware.svg'
import { useSiteContext } from '@context/SiteContext'
import useAuth from '@hooks/useAuth'
import useToast from '@hooks/useToast'
import { A } from '@solidjs/router'
import { IconLogout, IconMenuDeep } from '@tabler/icons-solidjs'
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) {
      console.log({
        status: 'danger',
        title: 'Logout fail!',
        closable: false,
      })
    }
  }

  return (
    <header class="w-full navbar py-3 px-4 items-center justify-between bg-emerald-500">
      <div class="flex items-center justify-end">
        <A href="/" class="text-white flex items-center hover:text-white">
          <img src={fuwareLogo} class="w-8" alt="Fuware logo" />
          <span class="ml-2 text-2xl">Fuware</span>
        </A>
      </div>
      <Show when={store.auth}>
        <div class="flex items-center justify-end">
          <div class="avatar hidden lg:block">
            <div class="w-9 mask mask-hexagon">
              <img
                src={`https://ui-avatars.com/api/?name=${store.userInfo?.name}`}
                alt="avatar"
              />
            </div>
          </div>
          <A
            href="/me"
            class="mx-3 text-white hover:text-white hidden lg:block"
          >
            {store.userInfo?.name}
          </A>
          <button class="btn btn-ghost btn-sm hidden lg:block" onClick={logOut}>
            <IconLogout size={16} />
          </button>
          <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>
  )
}
