'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' }
  }
]

function ActionMenu({ row }: { row: any }) {
  const [open, { set: setOpen }] = useToggle(false)
  const cert = row.original?.cert
  const { data, loading, runAsync, refresh } = useRequest(
    async () => {
      const r = await fetch(`/~/api/enrollments/${row.id}`, {
        method: 'GET'
      })

      return (await r.json()) as {
        cancel_policy?: any
        lock?: { hash: string }
      }
    },
    {
      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
          runAsync()
        }}
      >
        <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}
                lock={data?.lock}
                onSuccess={onSuccess}
              />
            </>
          )}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}

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

function DownloadItem({ id, onSuccess, ...props }: ItemProps) {
  const { runAsync, loading } = useRequest(
    async () => {
      return await fetch(`/~/api/enrollments/${id}/download`)
    },
    {
      manual: true
    }
  )

  const download = async (e: Event) => {
    e.preventDefault()

    try {
      const r = await runAsync()
      const { presigned_url } = (await r.json()) as {
        presigned_url: string
      }

      window.open(presigned_url, '_blank')
      onSuccess?.()
    } catch {}
  }

  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 remove = 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 daysRemaining = lock?.ttl ? getDaysRemaining(lock.ttl) : null

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

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

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: 'PATCH',
      headers: new Headers({ 'Content-Type': 'application/json' }),
      body: JSON.stringify({ lock_hash: lock?.hash })
    })

    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">
              cancela 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>
  )
}
