'use client'

import type { CellContext, ColumnDef } from '@tanstack/react-table'
import {
  CircleCheckIcon,
  CircleIcon,
  CircleOffIcon,
  CircleXIcon,
  HelpCircleIcon,
  TimerIcon,
  type LucideIcon
} from 'lucide-react'

import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
import { Badge } from '@repo/ui/components/ui/badge'
import { Checkbox } from '@repo/ui/components/ui/checkbox'
import { Progress } from '@repo/ui/components/ui/progress'
import { cn, 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.
type Course = {
  id: string
  name: string
}

export type Enrollment = {
  id: string
  name: string
  course: Course
  status: string
  progress: string
  created_at: string
}

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

export const statuses: Record<
  string,
  { icon: LucideIcon; color?: string; label: string }
> = {
  PENDING: {
    icon: CircleIcon,
    label: 'Não iniciado'
  },
  IN_PROGRESS: {
    icon: TimerIcon,
    color: 'text-blue-400 [&_svg]:text-blue-500',
    label: 'Em andamento'
  },
  COMPLETED: {
    icon: CircleCheckIcon,
    color: 'text-green-400 [&_svg]:text-background [&_svg]:fill-green-500',
    label: 'Aprovado'
  },
  FAILED: {
    icon: CircleXIcon,
    color: 'text-red-400 [&_svg]:text-red-500',
    label: 'Reprovado'
  },
  CANCELED: {
    icon: CircleOffIcon,
    color: 'text-orange-400 [&_svg]:text-orange-500',
    label: 'Cancelado'
  }
}

const defaultIcon = {
  icon: HelpCircleIcon
}

const statusTranslate: Record<string, string> = {
  PENDING: 'Não iniciado',
  IN_PROGRESS: 'Em andamento',
  COMPLETED: 'Aprovado',
  FAILED: 'Reprovado',
  CANCELED: 'Cancelado'
}

export const columns: ColumnDef<Enrollment>[] = [
  {
    id: 'select',
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && 'indeterminate')
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Selecionar tudo"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Selecionar linha"
      />
    )
  },
  {
    header: 'Colaborador',
    enableHiding: false,
    cell: ({ row: { original } }) => {
      const { user } = original

      return (
        <div className="flex gap-2.5 items-center">
          <Avatar className="size-12">
            <AvatarFallback>{initials(user.name)}</AvatarFallback>
          </Avatar>

          <ul>
            <li className="font-bold truncate max-w-62">{user.name}</li>
            <li className="text-muted-foreground text-sm truncate max-w-62">
              {user.email}
            </li>
          </ul>
        </div>
      )
    }
  },
  {
    accessorKey: 'course.name',
    header: 'Curso',
    enableHiding: false,
    cell: ({ row: { original } }) => (
      <abbr className="truncate max-w-62 block" title={original.course.name}>
        {original.course.name}
      </abbr>
    )
  },
  {
    accessorKey: 'status',
    header: 'Status',
    enableHiding: false,
    cell: ({ row: { original } }) => {
      const status = statusTranslate[original.status] ?? original.status
      const { icon: Icon, color } = statuses?.[original.status] ?? defaultIcon

      return (
        <Badge variant="outline" className={cn(color, ' px-1.5')}>
          <Icon className={cn('stroke-2', color)} />
          {status}
        </Badge>
      )
    }
  },
  {
    accessorKey: 'progress',
    header: 'Progresso',
    enableHiding: false,
    cell: ({ row: { original } }) => (
      <div className="flex gap-2.5 items-center ">
        <Progress value={Number(original.progress)} className="w-32" />
        <span className="text-xs">{original.progress}%</span>
      </div>
    )
  },
  {
    accessorKey: 'created_at',
    header: 'Matriculado em',
    enableSorting: true,
    enableHiding: true,
    cell: cellDate
  },
  {
    accessorKey: 'started_at',
    header: 'Iniciado em',
    enableSorting: true,
    enableHiding: true,
    cell: cellDate
  },
  {
    accessorKey: 'completed_at',
    header: 'Aprovado em',
    enableSorting: true,
    enableHiding: true,
    cell: cellDate
  },
  {
    accessorKey: 'failed_at',
    header: 'Reprovado em',
    enableSorting: true,
    enableHiding: true,
    cell: cellDate
  },
  {
    accessorKey: 'canceled_at',
    header: 'Cancelado em',
    enableSorting: true,
    enableHiding: true,
    cell: cellDate
  }
]

function cellDate<TData>({
  row: { original },
  cell: { column }
}: CellContext<TData, unknown>) {
  const accessorKey = column.columnDef.accessorKey as keyof TData
  const value = original?.[accessorKey]

  if (value) {
    return formatted.format(new Date(value as string))
  }

  return <></>
}
