'use client'

import type { ColumnDef } from '@tanstack/react-table'
import { useRequest, useToggle } from 'ahooks'
import {
  CircleXIcon,
  EllipsisVerticalIcon,
  FileBadgeIcon,
  HelpCircleIcon,
  LockOpenIcon
} from 'lucide-react'
import type { ComponentProps, MouseEvent } from 'react'
import { toast } from 'sonner'

import { Abbr } from '@repo/ui/components/abbr'
import {
  DataTableColumnDatetime,
  DataTableColumnHeader
} from '@repo/ui/components/data-table'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger
} from '@repo/ui/components/ui/alert-dialog'
import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
import { Badge } from '@repo/ui/components/ui/badge'
import { Button } from '@repo/ui/components/ui/button'
import { Checkbox } from '@repo/ui/components/ui/checkbox'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import { Progress } from '@repo/ui/components/ui/progress'
import { Spinner } from '@repo/ui/components/ui/spinner'
import { cn, initials } from '@repo/ui/lib/utils'

import { labels, statuses } from './data'

// 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 columns: ColumnDef<Enrollment>[] = [
  {
    id: 'select',
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && 'indeterminate')
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        className="cursor-pointer"
        aria-label="Selecionar tudo"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        disabled={!row.getCanSelect()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        className="cursor-pointer"
        aria-label="Selecionar linha"
      />
    )
  },
  {
    accessorKey: 'user',
    header: 'Colaborador',
    enableHiding: false,
    cell: ({ row }) => {
      const user = row.getValue('user') as { name: string; email: string }

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

          <ul>
            <li className="font-bold">
              <Abbr>{user.name}</Abbr>
            </li>
            <li className="text-muted-foreground text-sm">
              <Abbr>{user.email}</Abbr>
            </li>
          </ul>
        </div>
      )
    }
  },
  {
    accessorKey: 'course',
    header: 'Curso',
    enableHiding: false,
    cell: ({ row }) => {
      const { name } = row.getValue('course') as { name: string }
      return <Abbr>{name}</Abbr>
    }
  },
  {
    accessorKey: 'status',
    header: 'Status',
    enableHiding: false,
    cell: ({ row }) => {
      const s = row.getValue('status') as string
      const status = labels[s] ?? s
      const { icon: Icon, color } = statuses?.[s] ?? { icon: HelpCircleIcon }

      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 }) => {
      const progress = row.getValue('progress')

      return (
        <div className="flex gap-2.5 items-center ">
          <Progress value={Number(progress)} className="w-32" />
          <span className="text-xs">{String(progress)}%</span>
        </div>
      )
    }
  },
  {
    accessorKey: 'created_at',
    meta: { title: 'Cadastrado em' },
    enableSorting: true,
    enableHiding: true,
    header: ({ column }) => <DataTableColumnHeader column={column} />,
    cell: ({ row, column }) => (
      <DataTableColumnDatetime row={row} column={column} />
    )
  },
  {
    accessorKey: 'started_at',
    meta: { title: 'Iniciado em' },
    enableSorting: true,
    enableHiding: true,
    header: ({ column }) => <DataTableColumnHeader column={column} />,
    cell: ({ row, column }) => (
      <DataTableColumnDatetime row={row} column={column} />
    )
  },
  {
    accessorKey: 'completed_at',
    meta: { title: 'Concluído em' },
    enableSorting: true,
    enableHiding: true,
    header: ({ column }) => <DataTableColumnHeader column={column} />,
    cell: ({ row, column }) => (
      <DataTableColumnDatetime row={row} column={column} />
    )
  },
  {
    accessorKey: 'failed_at',
    meta: { title: 'Reprovado em' },
    enableSorting: true,
    enableHiding: true,
    header: ({ column }) => <DataTableColumnHeader column={column} />,
    cell: ({ row, column }) => (
      <DataTableColumnDatetime row={row} column={column} />
    )
  },
  {
    accessorKey: 'canceled_at',
    meta: { title: 'Cancelado em' },
    enableSorting: true,
    enableHiding: true,
    header: ({ column }) => <DataTableColumnHeader column={column} />,
    cell: ({ row, column }) => (
      <DataTableColumnDatetime row={row} column={column} />
    )
  },
  {
    id: 'actions',
    cell: ({ row }) => <ActionMenu row={row} />
  }
]

async function getEnrollment(id: string) {
  const r = await fetch(`/~/api/enrollments/${id}`, {
    method: 'GET'
  })
  await new Promise((r) => setTimeout(r, 150))

  return (await r.json()) as {
    cancel_policy?: any
    lock?: { hash: string }
  }
}

function ActionMenu({ row }: { row: any }) {
  const [open, { set: setOpen }] = useToggle(false)
  const cert = row.original?.cert
  const { data, loading, run, refresh } = useRequest(getEnrollment, {
    manual: true
  })

  const onSuccess = () => {
    refresh()
    setOpen(false)
  }

  return (
    <div className="flex justify-end items-center">
      <DropdownMenu
        modal={false}
        open={open}
        onOpenChange={(open) => {
          setOpen(open)
          if (data) return
          run(row.id)
        }}
      >
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            className="data-[state=open]:bg-muted text-muted-foreground cursor-pointer"
            size="icon-sm"
          >
            <EllipsisVerticalIcon />
            <span className="sr-only">Abrir menu</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-46 *:cursor-pointer">
          <DownloadItem
            id={row.id}
            disabled={!cert}
            onSuccess={() => setOpen(false)}
          />
          <DropdownMenuSeparator />
          {loading ? (
            <DropdownMenuItem disabled>
              <Spinner />
            </DropdownMenuItem>
          ) : (
            <>
              <RemoveDedupItem
                id={row.id}
                lock={data?.lock}
                onSuccess={onSuccess}
              />
              <CancelItem
                id={row.id}
                cancelPolicy={data?.cancel_policy}
                onSuccess={onSuccess}
              />
            </>
          )}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}

type ItemProps = ComponentProps<typeof DropdownMenuItem> & {
  id: string
  onSuccess?: () => void
}

function DownloadItem({ id, onSuccess, ...props }: ItemProps) {
  const [loading, { set }] = useToggle(false)

  const download = async (e: Event) => {
    e.preventDefault()
    set(true)
    const r = await fetch(`/~/api/enrollments/${id}/download`, {
      method: 'GET'
    })

    if (r.ok) {
      const { presigned_url } = (await r.json()) as { presigned_url: string }
      window.open(presigned_url, '_blank')

      set(false)
      onSuccess?.()
    }
  }

  return (
    <DropdownMenuItem onSelect={download} {...props}>
      {loading ? <Spinner /> : <FileBadgeIcon />} Baixar certificado
    </DropdownMenuItem>
  )
}

function RemoveDedupItem({
  id,
  lock,
  onSuccess,
  ...props
}: ItemProps & {
  lock?: { hash: string; ttl?: number }
}) {
  const [loading, { set }] = useToggle(false)
  const [open, { set: setOpen }] = useToggle(false)

  const cancel = async (e: MouseEvent<HTMLButtonElement>) => {
    e.preventDefault()
    set(true)

    if (!lock) return null

    const r = await fetch(`/~/api/enrollments/${id}/dedupwindow`, {
      method: 'DELETE',
      body: JSON.stringify({ lock_hash: lock.hash }),
      headers: new Headers({ 'Content-Type': 'application/json' })
    })

    if (r.ok) {
      toast.info('A proteção contra duplicação foi removida')
      setOpen(false)
      onSuccess?.()
    }
  }

  const getDaysRemaining = () => {
    if (!lock?.ttl) return null

    return new Date(lock.ttl * 1000).toLocaleString('pt-BR', {
      hour: '2-digit',
      minute: '2-digit',
      day: '2-digit',
      month: '2-digit',
      year: '2-digit'
    })
  }

  const daysRemaining = getDaysRemaining()

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        <DropdownMenuItem
          variant="destructive"
          onSelect={(e) => e.preventDefault()}
          disabled={!lock}
          {...props}
        >
          <LockOpenIcon /> Remover proteção
        </DropdownMenuItem>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Tem certeza absoluta?</AlertDialogTitle>
          <AlertDialogDescription>
            Esta ação não pode ser desfeita. Isso{' '}
            <span className="font-bold">
              remove a proteção contra duplicação permanentemente
            </span>{' '}
            desta matrícula.
          </AlertDialogDescription>
          {daysRemaining && (
            <AlertDialogDescription>
              Proteção contra duplicação válida até {daysRemaining}
            </AlertDialogDescription>
          )}
        </AlertDialogHeader>
        <AlertDialogFooter className="*:cursor-pointer">
          <AlertDialogCancel>Cancelar</AlertDialogCancel>
          <AlertDialogAction asChild>
            <Button onClick={cancel} disabled={loading} variant="destructive">
              {loading ? <Spinner /> : null} Continuar
            </Button>
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

function CancelItem({
  id,
  cancelPolicy,
  lock,
  onSuccess,
  ...props
}: ItemProps & {
  cancelPolicy?: object
  lock?: {
    hash: string
  }
}) {
  const [loading, { set }] = useToggle(false)
  const [open, { set: setOpen }] = useToggle(false)

  const cancel = async (e: MouseEvent<HTMLButtonElement>) => {
    e.preventDefault()
    set(true)

    const r = await fetch(`/~/api/enrollments/${id}/cancel`, {
      method: 'POST',
      headers: new Headers({ 'Content-Type': 'application/json' })
    })

    if (r.ok) {
      toast.info('A matrícula foi cancelada')
      setOpen(false)
      onSuccess?.()
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        <DropdownMenuItem
          variant="destructive"
          onSelect={(e) => e.preventDefault()}
          disabled={!cancelPolicy}
          {...props}
        >
          <CircleXIcon /> Cancelar
        </DropdownMenuItem>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Tem certeza absoluta?</AlertDialogTitle>
          <AlertDialogDescription>
            Esta ação não pode ser desfeita. Isso{' '}
            <span className="font-bold">
              cancelar permanentemente a matrícula
            </span>{' '}
            deste colaborador.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter className="*:cursor-pointer">
          <AlertDialogCancel>Cancelar</AlertDialogCancel>
          <AlertDialogAction asChild>
            <Button onClick={cancel} disabled={loading} variant="destructive">
              {loading ? <Spinner /> : null} Continuar
            </Button>
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
