'use client'

import { type ColumnDef } from '@tanstack/react-table'
import { EllipsisIcon, ReceiptTextIcon } from 'lucide-react'
import { NavLink } from 'react-router'

import { Abbr } from '@repo/ui/components/abbr'
import {
  DataTableColumnCpfCnpj,
  DataTableColumnHeaderSelect,
  DataTableColumnSelect
} from '@repo/ui/components/data-table'
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 { initials } from '@repo/ui/lib/utils'
import { columns as columns_, type Order } from '@repo/ui/routes/orders/columns'

import { Spinner } from '@repo/ui/components/ui/spinner'
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">
          <DropdownMenuItem asChild onSelect={(e) => e.preventDefault()}>
            <NavLink to={`${row.id}`}>
              {({ isPending }) => (
                <>
                  {isPending ? <Spinner /> : <ReceiptTextIcon />}
                  Detalhes
                </>
              )}
            </NavLink>
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <CopyToClipboardItem text={row.id} />
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}
