'use client'

import { useBoolean } from 'ahooks'
import { type ColumnDef } from '@tanstack/react-table'
import { CheckIcon, CopyIcon, EllipsisIcon } from 'lucide-react'

import {
  DataTableColumnSelect,
  DataTableColumnHeaderSelect
} from '@repo/ui/components/data-table'
import { Button } from '@repo/ui/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import { type User, columns as columns_ } from '@repo/ui/routes/users/columns'
import { cn } from '@repo/ui/lib/utils'
import { useRef } from 'react'

export type { User }

export const columns: ColumnDef<User>[] = [
  {
    id: 'select',
    header: DataTableColumnHeaderSelect,
    cell: DataTableColumnSelect,
    meta: { className: 'w-8' }
  },
  ...columns_,
  {
    id: 'action',
    cell: ActionMenu,
    meta: { className: 'w-12' }
  }
]

function ActionMenu({ row }: { row: any }) {
  return (
    <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"
          >
            <EllipsisIcon />
            <span className="sr-only">Abrir menu</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-36 *:cursor-pointer">
          <CopyToClipboardItem text={row.id} />
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}

export function CopyToClipboardItem({ text }: { text: string }) {
  const [isCopied, { setTrue, setFalse }] = useBoolean()
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  return (
    <DropdownMenuItem
      onSelect={(e) => e.preventDefault()}
      className={cn({ 'pointer-events-none': isCopied })}
      onClick={async () => {
        await navigator.clipboard.writeText(text)
        setTrue()

        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current)
        }

        timeoutRef.current = setTimeout(() => {
          setFalse()
          timeoutRef.current = null
        }, 3000)
      }}
    >
      {isCopied ? (
        <>
          <CheckIcon /> Copiado!
        </>
      ) : (
        <>
          <CopyIcon /> Copiar ID
        </>
      )}
    </DropdownMenuItem>
  )
}
