import { Button, Popover, PopoverButton, PopoverPanel } from '@headlessui/react'
import { Link, useFetcher, useRouteLoaderData } from 'react-router'

import { ChevronIcon } from '~/components/icons/chevron'
import { ProfileIcon } from '~/components/icons/profile'
import { APP } from '~/configs/meta'
import type { loader } from '~/routes/_admin.lg-admin'

export const Navbar = () => {
  const loaderData = useRouteLoaderData<typeof loader>('routes/_admin.lg-admin')
  const staffData = loaderData?.staffData
  const fetcher = useFetcher()

  return (
    <div className="flex h-20 items-center justify-between border-b border-[#ECECEC] bg-white px-10 py-5">
      <Link
        to="/"
        className="h-full"
      >
        <img
          src={APP.logo}
          alt={APP.title}
          className="h-3/4 w-auto sm:h-full"
        />
      </Link>
      <div className="flex items-center gap-x-8">
        <Popover className="relative">
          <PopoverButton className="flex w-3xs cursor-pointer items-center justify-between focus:outline-none">
            <div className="flex items-center">
              {staffData?.profile_picture === '' ? (
                <ProfileIcon className="mr-3 h-8 w-8 rounded-full bg-[#C4C4C4]" />
              ) : (
                <img
                  src={staffData?.profile_picture}
                  alt={staffData?.name}
                  className="mr-3 h-8 w-8 rounded-full bg-[#C4C4C4] object-cover"
                />
              )}

              <span className="text-xs">{staffData?.name}</span>
            </div>
            <ChevronIcon className="opacity-50" />
          </PopoverButton>
          <PopoverPanel
            anchor={{ to: 'bottom', gap: '8px' }}
            transition
            className="flex w-3xs flex-col rounded-xl border border-[#ECECEC] bg-white p-3 transition duration-200 ease-in-out data-[closed]:-translate-y-1 data-[closed]:opacity-0"
          >
            <fetcher.Form
              method="POST"
              action="/actions/admin/logout"
              className="grid"
            >
              <Button
                type="submit"
                className="cursor-pointer rounded p-1 hover:bg-[#707FDD]/10 hover:text-[#5363AB]"
              >
                Logout
              </Button>
            </fetcher.Form>
          </PopoverPanel>
        </Popover>
      </div>
    </div>
  )
}
