'use client'

import type { WebhookEndpointListItem } from '@admin/actions/webhooks'
import type { ColumnDef } from '@tanstack/react-table'
import { SortIndicator } from '@admin/components/shared/sort-indicator'
import { Badge } from '@admin/components/ui/badge'
import { Button } from '@admin/components/ui/button'
import { formatDistanceToNow } from 'date-fns'
import { WebhookActions } from './webhook-actions'
import { WebhookEnabledSwitch } from './webhook-enabled-switch'

interface WebhooksColumnsOptions {
  onEdit: (webhook: WebhookEndpointListItem) => void
  onDelete: (webhook: WebhookEndpointListItem) => void
}

export function createWebhooksColumns({
  onEdit,
  onDelete
}: WebhooksColumnsOptions): ColumnDef<WebhookEndpointListItem>[] {
  return [
    {
      accessorKey: 'name',
      size: 240,
      header: ({ column }) => {
        const sortDirection = column.getIsSorted()
        const sortLabel =
          sortDirection === 'asc'
            ? 'sorted ascending'
            : sortDirection === 'desc'
              ? 'sorted descending'
              : 'not sorted'

        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
            className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
            aria-label={`Sort by Name, ${sortLabel}`}
            aria-sort={
              sortDirection === 'asc'
                ? 'ascending'
                : sortDirection === 'desc'
                  ? 'descending'
                  : 'none'
            }
          >
            <span className="truncate">Name</span>
            <SortIndicator direction={sortDirection} />
          </Button>
        )
      },
      cell: ({ row }) => <span className="truncate font-medium">{row.original.name}</span>,
      enableHiding: false
    },
    {
      accessorKey: 'url',
      size: 320,
      header: ({ column }) => {
        const sortDirection = column.getIsSorted()
        const sortLabel =
          sortDirection === 'asc'
            ? 'sorted ascending'
            : sortDirection === 'desc'
              ? 'sorted descending'
              : 'not sorted'

        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
            className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
            aria-label={`Sort by URL, ${sortLabel}`}
            aria-sort={
              sortDirection === 'asc'
                ? 'ascending'
                : sortDirection === 'desc'
                  ? 'descending'
                  : 'none'
            }
          >
            <span className="truncate">URL</span>
            <SortIndicator direction={sortDirection} />
          </Button>
        )
      },
      cell: ({ row }) => (
        <span className="truncate font-mono text-xs text-muted-foreground">{row.original.url}</span>
      )
    },
    {
      accessorKey: 'enabled',
      size: 110,
      header: ({ column }) => {
        const sortDirection = column.getIsSorted()
        const sortLabel =
          sortDirection === 'asc'
            ? 'sorted ascending'
            : sortDirection === 'desc'
              ? 'sorted descending'
              : 'not sorted'

        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
            className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
            aria-label={`Sort by Enabled, ${sortLabel}`}
            aria-sort={
              sortDirection === 'asc'
                ? 'ascending'
                : sortDirection === 'desc'
                  ? 'descending'
                  : 'none'
            }
          >
            <span className="truncate">Enabled</span>
            <SortIndicator direction={sortDirection} />
          </Button>
        )
      },
      cell: ({ row }) => <WebhookEnabledSwitch webhook={row.original} />
    },
    {
      accessorKey: 'eventCount',
      size: 100,
      header: ({ column }) => {
        const sortDirection = column.getIsSorted()
        const sortLabel =
          sortDirection === 'asc'
            ? 'sorted ascending'
            : sortDirection === 'desc'
              ? 'sorted descending'
              : 'not sorted'

        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
            className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
            aria-label={`Sort by Events, ${sortLabel}`}
            aria-sort={
              sortDirection === 'asc'
                ? 'ascending'
                : sortDirection === 'desc'
                  ? 'descending'
                  : 'none'
            }
          >
            <span className="truncate">Events</span>
            <SortIndicator direction={sortDirection} />
          </Button>
        )
      },
      cell: ({ row }) => <span className="tabular-nums">{row.original.eventCount}</span>
    },
    {
      accessorKey: 'lastDeliveryAt',
      size: 220,
      header: ({ column }) => {
        const sortDirection = column.getIsSorted()
        const sortLabel =
          sortDirection === 'asc'
            ? 'sorted ascending'
            : sortDirection === 'desc'
              ? 'sorted descending'
              : 'not sorted'

        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
            className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
            aria-label={`Sort by Last delivery, ${sortLabel}`}
            aria-sort={
              sortDirection === 'asc'
                ? 'ascending'
                : sortDirection === 'desc'
                  ? 'descending'
                  : 'none'
            }
          >
            <span className="truncate">Last delivery</span>
            <SortIndicator direction={sortDirection} />
          </Button>
        )
      },
      cell: ({ row }) =>
        row.original.lastDeliveryAt ? (
          <span className="flex min-w-0 items-center gap-2">
            <Badge variant={row.original.lastDeliverySuccess ? 'outline' : 'destructive'}>
              {row.original.lastDeliverySuccess ? 'Delivered' : 'Failed'}
            </Badge>
            <span className="truncate text-xs text-muted-foreground">
              {formatDistanceToNow(new Date(row.original.lastDeliveryAt), {
                addSuffix: true
              })}
            </span>
          </span>
        ) : (
          <span className="text-muted-foreground">—</span>
        )
    },
    {
      accessorKey: 'createdAt',
      size: 120,
      header: ({ column }) => {
        const sortDirection = column.getIsSorted()
        const sortLabel =
          sortDirection === 'asc'
            ? 'sorted ascending'
            : sortDirection === 'desc'
              ? 'sorted descending'
              : 'not sorted'

        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
            className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
            aria-label={`Sort by Created, ${sortLabel}`}
            aria-sort={
              sortDirection === 'asc'
                ? 'ascending'
                : sortDirection === 'desc'
                  ? 'descending'
                  : 'none'
            }
          >
            <span className="truncate">Created</span>
            <SortIndicator direction={sortDirection} />
          </Button>
        )
      },
      cell: ({ row }) => (
        <div className="text-sm">
          {new Date(row.original.createdAt).toLocaleDateString('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric'
          })}
        </div>
      )
    },
    {
      id: 'actions',
      size: 64,
      enableResizing: false,
      meta: { width: '64px' },
      header: () => <span className="sr-only">Actions</span>,
      cell: ({ row }) => (
        <div className="flex justify-end">
          <WebhookActions webhook={row.original} onEdit={onEdit} onDelete={onDelete} />
        </div>
      )
    }
  ]
}
