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

import { useToggle } from 'ahooks'
import {
  EllipsisVerticalIcon,
  PencilIcon,
  UserRoundMinusIcon
} from 'lucide-react'
import { Suspense } 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,
  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 {
    data: users
  }
}

export default function Route({ loaderData: { data } }) {
  return (
    <>
      <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>

      <Suspense fallback={<Skeleton />}>
        <Await resolve={data}>
          {({ items }) => {
            return (
              <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="bg-card border-border/50 hover:shadow-muted-foreground/10 hover:border-muted group
                                 relative overflow-hidden rounded-2xl border p-8 transition-all duration-300  hover:shadow-2xl"
                    >
                      <ActionMenu id={id} />
                      <div
                        className="from-muted-foreground/5 absolute inset-0 bg-gradient-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"
        >
          <EllipsisVerticalIcon />
          <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>
        <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) => {
    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">
          <AlertDialogCancel>Cancelar</AlertDialogCancel>
          <AlertDialogAction asChild>
            <Button onClick={revoke} disabled={loading} variant="destructive">
              {loading ? <Spinner /> : null} Continuar
            </Button>
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
