'use client';

import { Badge } from '@tale/ui/badge';
import { Text } from '@tale/ui/text';
import type { ColumnDef } from '@tanstack/react-table';
import { useMemo } from 'react';

import { TableDateCell } from '@/app/components/ui/data-display/table-date-cell';
import type { Doc } from '@/convex/_generated/dataModel';
import { useT } from '@/lib/i18n/client';

type AuditLog = Doc<'auditLogs'>;

interface AuditLogTableConfig {
  columns: ColumnDef<AuditLog>[];
  stickyLayout: boolean;
  pageSize: number;
}

interface UseAuditLogTableConfigOptions {
  resolveEmail?: (log: AuditLog) => string | undefined;
}

export function useAuditLogTableConfig(
  options?: UseAuditLogTableConfigOptions,
): AuditLogTableConfig {
  const resolveEmail = options?.resolveEmail;
  const { t } = useT('settings');

  const columns = useMemo<ColumnDef<AuditLog>[]>(
    () => [
      {
        accessorKey: 'timestamp',
        header: () => (
          <Text as="span" align="right" className="block w-full">
            {t('logs.audit.columns.timestamp')}
          </Text>
        ),
        size: 140,
        meta: {
          headerLabel: t('logs.audit.columns.timestamp'),
          align: 'right' as const,
        },
        cell: ({ row }) => (
          <TableDateCell
            date={row.original.timestamp}
            customFormat="MMM D, YYYY HH:mm"
            alignRight
          />
        ),
      },
      {
        accessorKey: 'action',
        header: t('logs.audit.columns.action'),
        cell: ({ row }) => (
          <Text as="span" variant="label">
            {t('logs.audit.actionLabels.' + row.original.action, {
              defaultValue: row.original.action.replace(/_/g, ' '),
            })}
          </Text>
        ),
        size: 240,
      },
      {
        accessorKey: 'actorEmail',
        header: t('logs.audit.columns.actor'),
        meta: { skeleton: { type: 'two-line' as const } },
        cell: ({ row }) => {
          const email = resolveEmail?.(row.original) ?? row.original.actorEmail;
          return (
            <div className="flex flex-col gap-0.5">
              <Text as="span" variant="body" truncate>
                {email ?? row.original.actorId}
              </Text>
              {email && (
                <Text as="span" variant="muted" truncate className="text-xs">
                  {row.original.actorId}
                </Text>
              )}
            </div>
          );
        },
        size: 220,
      },
      {
        accessorKey: 'resourceType',
        header: t('logs.audit.columns.resource'),
        cell: ({ row }) => (
          <Text as="span" variant="body" className="capitalize">
            {t('logs.audit.resourceTypeLabels.' + row.original.resourceType, {
              defaultValue: row.original.resourceType.replace(/_/g, ' '),
            })}
          </Text>
        ),
        size: 120,
      },
      {
        accessorKey: 'resourceName',
        header: t('logs.audit.columns.target'),
        cell: ({ row }) => (
          <Text
            as="span"
            variant="muted"
            truncate
            className="block max-w-[200px]"
          >
            {row.original.resourceName ?? row.original.resourceId ?? '-'}
          </Text>
        ),
        size: 200,
      },
      {
        accessorKey: 'category',
        header: t('logs.audit.columns.category'),
        meta: { skeleton: { type: 'badge' as const } },
        cell: ({ row }) => (
          <Badge variant="outline" className="capitalize">
            {t('logs.audit.categoryLabels.' + row.original.category)}
          </Badge>
        ),
        size: 100,
      },
      {
        accessorKey: 'status',
        header: t('logs.audit.columns.status'),
        meta: { skeleton: { type: 'badge' as const } },
        cell: ({ row }) => {
          const status = row.original.status;
          return (
            <Badge
              variant={
                status === 'success'
                  ? 'green'
                  : status === 'denied'
                    ? 'yellow'
                    : 'destructive'
              }
            >
              {t('logs.audit.statusLabels.' + status)}
            </Badge>
          );
        },
        size: 100,
      },
    ],
    [t, resolveEmail],
  );

  return { columns, stickyLayout: true, pageSize: 30 };
}
