'use client'

import { type ColumnDef } from '@tanstack/react-table'
import { EllipsisIcon } from 'lucide-react'

import { Abbr } from '@repo/ui/components/abbr'
import { Button } from '@repo/ui/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
import { initials } from '@repo/ui/lib/utils'
import {
  DataTableColumnCpfCnpj,
  DataTableColumnHeaderSelect,
  DataTableColumnSelect
} from '@repo/ui/components/data-table'
import { columns as columns_, type Order } from '@repo/ui/routes/orders/columns'

import { CopyToClipboardItem } from '../_app.users._index/columns'

export type { Order }

export const columns: ColumnDef<Order>[] = [
  {
    id: 'select',
    header: DataTableColumnHeaderSelect,
    cell: DataTableColumnSelect,
    meta: { className: 'w-8' }
  },
  {
    header: 'Comprador',
    cell: ({ row }) => {
      const { name, email } = row.original

      return (
        <div className="flex gap-2.5 items-center">
          <Avatar className="size-10 hidden lg:block">
            <AvatarFallback className="border">{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>
      )
    }
  },
  {
    accessorKey: 'cpf_cnpj',
    header: 'CPF/CNPJ',
    // @ts-ignore
    accessorFn: ({ cpf, cnpj }) => cpf ?? cnpj,
    cell: DataTableColumnCpfCnpj
  },
  ...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>
  )
}
