'use client';

import type { Column, ColumnDef } from '@tanstack/react-table';
import { Badge } from '@/components/ui/badge';
import { DataTableColumnHeader } from '@/components/ui/table/data-table-column-header';
import { getAuditActionLabel, getAuditModuleLabel } from '../constants/audit-log-options';
import type { AuditLog } from '../api/types';

export const auditLogColumns: ColumnDef<AuditLog>[] = [
  {
    id: 'created_at',
    accessorKey: 'created_at',
    header: ({ column }: { column: Column<AuditLog, unknown> }) => (
      <DataTableColumnHeader column={column} title='วันที่' />
    ),
    cell: ({ row }) => (
      <div className='min-w-[160px]'>
        {new Intl.DateTimeFormat('th-TH', {
          dateStyle: 'medium',
          timeStyle: 'short'
        }).format(new Date(row.original.created_at))}
      </div>
    )
  },
  {
    id: 'user_name',
    accessorKey: 'user_name',
    header: ({ column }: { column: Column<AuditLog, unknown> }) => (
      <DataTableColumnHeader column={column} title='ผู้ใช้งาน' />
    ),
    cell: ({ row }) => (
      <div className='flex min-w-[200px] flex-col'>
        <span className='font-medium'>{row.original.user_name ?? 'ระบบ'}</span>
        <span className='text-muted-foreground text-xs'>{row.original.user_email ?? '-'}</span>
      </div>
    )
  },
  {
    id: 'module_name',
    accessorKey: 'module_name',
    header: ({ column }: { column: Column<AuditLog, unknown> }) => (
      <DataTableColumnHeader column={column} title='โมดูล' />
    ),
    cell: ({ row }) => <Badge variant='outline'>{getAuditModuleLabel(row.original.module_name)}</Badge>
  },
  {
    id: 'action',
    accessorKey: 'action',
    header: ({ column }: { column: Column<AuditLog, unknown> }) => (
      <DataTableColumnHeader column={column} title='รายการ' />
    ),
    cell: ({ row }) => <Badge>{getAuditActionLabel(row.original.action)}</Badge>
  },
  {
    id: 'details',
    accessorKey: 'details',
    header: ({ column }: { column: Column<AuditLog, unknown> }) => (
      <DataTableColumnHeader column={column} title='รายละเอียด' />
    ),
    cell: ({ row }) => (
      <div className='min-w-[320px] space-y-1'>
        <div className='text-sm'>{row.original.details}</div>
        <div className='text-muted-foreground text-xs'>
          {row.original.ip_address ? `IP ${row.original.ip_address}` : 'ไม่ระบุ IP'}
        </div>
      </div>
    )
  }
];
