'use client'

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

import {
  DataTableColumnHeaderSelect,
  DataTableColumnSelect
} from '@repo/ui/components/data-table'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger
} from '@repo/ui/components/ui/alert-dialog'

import { Button } from '@repo/ui/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import { Spinner } from '@repo/ui/components/ui/spinner'
import {
  type Enrollment,
  columns as columns_
} from '@repo/ui/routes/enrollments/columns'

export type { Enrollment }

export const columns: ColumnDef<Enrollment>[] = [
  {
    id: 'select',
    header: DataTableColumnHeaderSelect,
    cell: DataTableColumnSelect,
    meta: { className: 'w-9' }
  },
  ...columns_,
  {
    id: 'action',
    cell: ActionMenu,
    meta: { className: 'w-12' }
  }
]

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"
          >
            <EllipsisIcon />
            <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">
          <AlertDialogAction asChild>
            <Button onClick={cancel} disabled={loading} variant="destructive">
              {loading ? <Spinner /> : null} Continuar
            </Button>
          </AlertDialogAction>
          <AlertDialogCancel>Cancelar</AlertDialogCancel>
        </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">
          <AlertDialogAction asChild>
            <Button onClick={cancel} disabled={loading} variant="destructive">
              {loading ? <Spinner /> : null} Continuar
            </Button>
          </AlertDialogAction>
          <AlertDialogCancel>Cancelar</AlertDialogCancel>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
