import { Link, useFetcher, useRouteLoaderData } from 'react-router'

import { Button } from '~/components/ui/button'
import { APP } from '~/configs/meta'
import { useNewsContext } from '~/contexts/news'
import type { loader } from '~/routes/_news'

export const HeaderTop = () => {
  const { setIsLoginOpen } = useNewsContext()
  const loaderData = useRouteLoaderData<typeof loader>('routes/_news')
  const { userData } = loaderData || {}
  const fetcher = useFetcher()

  return (
    <div className="flex h-[60px] items-center justify-between bg-white px-5 align-middle sm:h-[100px] sm:gap-[15px] sm:px-[50px] sm:py-[20px]">
      <Link
        to="/"
        className="mt-2 h-full py-2"
      >
        <img
          src={APP.logo}
          alt={APP.title}
          className="h-3/4 w-auto sm:h-full"
        />
      </Link>
      <h1 className="hidden h-full items-center py-1.5 text-4xl font-extrabold whitespace-pre-line text-[#2E2F7C] uppercase sm:flex">
        {APP.description}
      </h1>
      <div className="flex items-center gap-[15px]">
        {userData ? (
          <fetcher.Form
            method="POST"
            action="/actions/logout"
          >
            <Button
              variant="outline"
              className="hidden sm:flex"
              type="submit"
              disabled={fetcher.state !== 'idle'}
              isLoading={fetcher.state !== 'idle'}
            >
              Logout
            </Button>
          </fetcher.Form>
        ) : (
          <Button
            variant="outline"
            className="hidden sm:block"
            onClick={() => setIsLoginOpen(true)}
          >
            Masuk
          </Button>
        )}
      </div>
    </div>
  )
}
