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

import { useToggle } from 'ahooks'
import { EllipsisIcon, PencilIcon, UserRoundMinusIcon } from 'lucide-react'
import { Suspense, type MouseEvent } from 'react'
import { Await, NavLink, useParams, useRevalidator } from 'react-router'
import { toast } from 'sonner'

import { Abbr } from '@repo/ui/components/abbr'
import { Skeleton } from '@repo/ui/components/skeleton'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger
} from '@repo/ui/components/ui/alert-dialog'
import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
import { Button } from '@repo/ui/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { initials } from '@repo/ui/lib/utils'
import { request as req } from '@repo/util/request'

type Admin = {
  sk: string
  name: string
  email: string
}

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

export async function loader({ context, request, params }: Route.LoaderArgs) {
  const users = req({
    url: `/orgs/${params.orgid}/admins`,
    context,
    request
  }).then((r) => r.json())

  return { users }
}

export default function Route({ loaderData: { users } }: Route.ComponentProps) {
  return (
    <Suspense fallback={<Skeleton />}>
      <div className="space-y-0.5 mb-8">
        <h1 className="text-2xl font-bold tracking-tight">Gestores</h1>
        <p className="text-muted-foreground">
          Adicione gestores e organize sua equipe de forma prática.
        </p>
      </div>

      <Await resolve={users}>
        {({ items }) => (
          <div className="grid gap-4 lg:gap-8 md:grid-cols-2 lg:grid-cols-3">
            {items.map(({ sk, name, email }: Admin) => {
              const [_, id] = sk.split('#')

              return (
                <section
                  key={id}
                  className="group relative p-8 overflow-hidden bg-card
                             border border-border/50 rounded-2xl
                             hover:shadow-muted-foreground/10 hover:border-muted
                             hover:shadow-2xl transition-all duration-300"
                >
                  <ActionMenu id={id} />
                  <div
                    className="from-muted-foreground/5 absolute inset-0
                               bg-linear-to-br to-transparent opacity-0
                               transition-opacity duration-300
                               group-hover:opacity-100"
                  />
                  <div className="relative flex flex-col items-center text-center">
                    <div className="relative mb-6">
                      <Avatar className="size-24 lg:size-28">
                        <AvatarFallback className="text-2xl">
                          {initials(name)}
                        </AvatarFallback>
                      </Avatar>
                    </div>

                    <div className="mb-6">
                      <h1 className="mb-2 text-xl font-bold">
                        <Abbr>{name}</Abbr>
                      </h1>
                      <p
                        className="text-muted-foreground bg-muted/50 inline-block
                                   rounded-full px-4 py-1.5 text-sm font-medium"
                      >
                        <Abbr>{email}</Abbr>
                      </p>
                    </div>
                  </div>
                </section>
              )
            })}
          </div>
        )}
      </Await>
    </Suspense>
  )
}

function ActionMenu({ id }: { id: string }) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          className="data-[state=open]:bg-muted text-muted-foreground
                     cursor-pointer absolute z-1 right-4 top-4"
          size="icon-sm"
        >
          <EllipsisIcon />
          <span className="sr-only">Abrir menu</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-46 *:cursor-pointer">
        <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
          <NavLink to={`../users/${id}`}>
            {({ isPending }) => (
              <>
                {isPending ? <Spinner /> : <PencilIcon />}
                Editar
              </>
            )}
          </NavLink>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <RevokeItem id={id} />
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function RevokeItem({ id }: { id: string }) {
  const [loading, { set }] = useToggle(false)
  const { orgid } = useParams()
  const { revalidate } = useRevalidator()

  const revoke = async (e: MouseEvent<HTMLButtonElement>) => {
    e.preventDefault()
    set(true)

    const r = await fetch(`/~/api/orgs/${orgid}/admins/${id}`, {
      method: 'DELETE'
    })

    if (r.ok) {
      toast.info('Os privilégios foram revogados')
      revalidate()
    }
  }

  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <DropdownMenuItem
          variant="destructive"
          onSelect={(e) => e.preventDefault()}
        >
          <UserRoundMinusIcon /> Revogar privilégios
        </DropdownMenuItem>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Tem certeza absoluta?</AlertDialogTitle>
          <AlertDialogDescription>
            Esta ação não pode ser desfeita. Isso{' '}
            <span className="font-bold">
              revogará permanentemente os privilégios
            </span>{' '}
            deste gestor.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter className="*:cursor-pointer">
          <AlertDialogAction asChild>
            <Button onClick={revoke} disabled={loading} variant="destructive">
              {loading ? <Spinner /> : null} Continuar
            </Button>
          </AlertDialogAction>
          <AlertDialogCancel>Cancelar</AlertDialogCancel>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
