'use client'

import { formatCPF } from '@brazilian-utils/brazilian-utils'
import { type ColumnDef } from '@tanstack/react-table'
import { useToggle } from 'ahooks'
import {
  EllipsisVerticalIcon,
  PencilIcon,
  UserRoundMinusIcon
} from 'lucide-react'
import { NavLink, useParams } from 'react-router'
import { toast } from 'sonner'

import { Abbr } from '@/components/abbr'
import { useDataTable } from '@/components/data-table/data-table'
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'

// This type is used to define the shape of our data.
// You can use a Zod schema here if you want.
export type User = {
  id: string
  name: string
  email: string
  cpf?: string
  cnpj?: string
}

const formatted = new Intl.DateTimeFormat('pt-BR', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
  hour: '2-digit',
  minute: '2-digit'
})

export const columns: ColumnDef<User>[] = [
  {
    header: 'Colaborador',
    cell: ({ row }) => {
      const { name, email } = row.original

      return (
        <div className="flex gap-2.5 items-center">
          <Avatar className="size-10 hidden lg:block">
            <AvatarFallback>{initials(name)}</AvatarFallback>
          </Avatar>

          <ul>
            <li className="font-bold">
              <Abbr>{name}</Abbr>
            </li>
            <li className="text-muted-foreground text-sm">
              <Abbr>{email}</Abbr>
            </li>
          </ul>
        </div>
      )
    }
  },
  {
    header: 'CPF',
    cell: ({ row }) => {
      const { cpf } = row.original

      if (cpf) {
        return <>{formatCPF(cpf)}</>
      }

      return <></>
    }
  },
  {
    header: 'Último accesso',
    cell: ({ row }) => {
      // Post-migration: rename `lastLogin` to `last_login`
      if (row.original?.lastLogin) {
        const lastLogin = new Date(row.original.lastLogin)
        return formatted.format(lastLogin)
      }

      return <></>
    }
  },
  {
    header: 'Cadastrado em',
    meta: {
      className: 'w-1/12'
    },
    cell: ({ row }) => {
      const created_at = new Date(row.original.createDate)
      return formatted.format(created_at)
    }
  },
  {
    id: 'actions',
    cell: ({ row }) => (
      <div className="flex justify-end items-center">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              className="data-[state=open]:bg-muted text-muted-foreground cursor-pointer"
              size="icon-sm"
            >
              <EllipsisVerticalIcon />
              <span className="sr-only">Abrir menu</span>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-36 *:cursor-pointer">
            <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
              <NavLink to={`${row.id}`}>
                {({ isPending }) => (
                  <>
                    {isPending ? <Spinner /> : <PencilIcon />}
                    Editar
                  </>
                )}
              </NavLink>
            </DropdownMenuItem>
            <UnlinkMenuItem userId={row.id} />
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    )
  }
]

function UnlinkMenuItem({ userId }: { userId: string }) {
  const [loading, { set }] = useToggle(false)
  const { orgid } = useParams()
  const { table } = useDataTable<User>()

  return (
    <DropdownMenuItem
      variant="destructive"
      disabled={loading}
      onClick={async (e) => {
        e.preventDefault()
        set(true)

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

        if (r.ok) {
          toast.info('O colaborador foi desvinculado')
          // @ts-ignore
          table.options.meta?.removeRow?.(userId)
        }
      }}
    >
      {loading ? <Spinner /> : <UserRoundMinusIcon />} Desvincular
    </DropdownMenuItem>
  )
}
