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

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

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

export function meta() {
  return [
    {
      title: 'Editar colaborador'
    }
  ]
}

export async function loader({ params, request, context }: Route.LoaderArgs) {
  const { id } = params
  const r = await req({
    url: `/users/${id}`,
    request,
    context
  })

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

  const data = await r.json()
  return { data } as { data: any }
}

export function shouldRevalidate({
  currentParams,
  nextParams
}: ShouldRevalidateFunctionArgs) {
  return currentParams.id !== nextParams.id
}

const links = [
  { to: '', title: 'Perfil', end: true },
  { to: 'emails', title: 'Emails' }
]

export default function Route({
  loaderData: { data: user }
}: Route.ComponentProps) {
  return (
    <div className="space-y-2.5">
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink asChild>
              <Link to="../users">Colaboradores</Link>
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>Editar colaborador</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      <div className="lg:max-w-2xl mx-auto space-y-2.5">
        <div className="flex gap-2.5 items-center mb-5">
          <Avatar className="size-12">
            <AvatarFallback>{initials(user.name)}</AvatarFallback>
          </Avatar>

          <ul>
            <li className="font-bold text-lg">{user.name}</li>
            <li className="text-muted-foreground text-sm truncate max-lg:max-w-62">
              {user.email}
            </li>
          </ul>
        </div>

        <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 }} />
      </div>
    </div>
  )
}
