import type { Route } from './+types/layout'

import {
  NavLink,
  Outlet,
  Link,
  type ShouldRevalidateFunctionArgs
} from 'react-router'

import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator
} from '@repo/ui/components/ui/breadcrumb'
import { Tabs, TabsList, TabsTrigger } from '@repo/ui/components/ui/tabs'
import { request as req } from '@repo/util/request'

import { Container } from '@/components/container'
import { userContext } from '@repo/auth/context'
import type { User } from '@repo/auth/auth'

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Minha conta' }]
}

export async function loader({ request, context }: Route.LoaderArgs) {
  const user = context.get(userContext) as User
  const r = await req({
    url: `/users/${user.sub}`,
    request,
    context
  })

  if (!r.ok) {
    throw new Response(null, { status: r.status })
  }

  return { data: await r.json() }
}

export function shouldRevalidate({}: ShouldRevalidateFunctionArgs) {
  return false
}

const links = [
  { to: '', title: 'Perfil', end: true },
  { to: 'emails', title: 'Emails' },
  { to: 'password', title: 'Senha' }
  // { to: 'orgs', title: 'Empresas' }
]

export default function Layout({ loaderData: { data } }: Route.ComponentProps) {
  return (
    <Container className="space-y-2.5">
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink asChild>
              <Link to="..">Meus cursos</Link>
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>Minha conta</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      <div className="lg:max-w-2xl mx-auto space-y-2.5">
        <Tabs>
          <TabsList>
            {links.map(({ to, title, ...props }, idx) => (
              <NavLink
                to={to}
                key={idx}
                className="aria-[current=page]:pointer-events-none"
                {...props}
              >
                {({ isActive }) => (
                  <TabsTrigger
                    data-state={isActive ? 'active' : ''}
                    value={title}
                    asChild
                  >
                    <span>{title}</span>
                  </TabsTrigger>
                )}
              </NavLink>
            ))}
          </TabsList>
        </Tabs>

        <Outlet context={{ user: data }} />
      </div>
    </Container>
  )
}
