'use client'

import { formatCNPJ, formatCPF } from '@brazilian-utils/brazilian-utils'
import { type ColumnDef } from '@tanstack/react-table'

import { Abbr } from '@repo/ui/components/abbr'
import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
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 Order = {
  id: string
  total: number
  status: 'pending' | 'processing' | 'success' | 'failed'
  payment_method: 'PIX' | 'CREDIT_CARD' | 'MANUAL' | 'failed'
  name: 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<Order>[] = [
  {
    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>{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: 'CNPJ/CPF',
    cell: ({ row }) => {
      const { cpf, cnpj } = row.original

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

      if (cnpj) {
        return <>{formatCNPJ(cnpj)}</>
      }

      return <></>
    }
  },
  {
    accessorKey: 'payment_method',
    header: 'Forma de pag.'
  },
  {
    accessorKey: 'status',
    header: 'Status'
  },
  {
    accessorKey: 'total',
    header: 'Valor total',
    cell: ({ row }) => {
      const amount = parseFloat(row.getValue('total'))
      const formatted = new Intl.NumberFormat('pt-BR', {
        style: 'currency',
        currency: 'BRL'
      }).format(amount)

      return <div className="font-medium">{formatted}</div>
    }
  },
  {
    header: 'Comprado em',
    cell: ({ row }) => {
      const createdAt = new Date(row.original.create_date)
      return formatted.format(createdAt)
    }
  },
  {
    header: 'Vencimento em',
    cell: ({ row }) => {
      try {
        const dueDate = new Date(row.original.due_date)
        return formatted.format(dueDate)
      } catch {
        return 'N/A'
      }
    }
  },
  {
    header: 'Pago em',
    cell: ({ row }) => {
      if (row.original.payment_date) {
        const createdAt = new Date(row.original.payment_date)
        return formatted.format(createdAt)
      }

      return <></>
    }
  }
]
