'use client';

import { useMemo } from 'react';
import type { ColumnDef } from '@tanstack/react-table';

import { Badge } from '@/components/ui/badge';
import type { AdministrationUser } from '@/types';

function formatDate(value?: string | null) {
  if (!value) return '-';
  return new Intl.DateTimeFormat('en-IN', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  }).format(new Date(value));
}

export function useUserColumns(): ColumnDef<AdministrationUser>[] {
  return useMemo(() => {
    return [
      {
        accessorKey: 'first_name',
        header: 'Name',
        cell: ({ row }) => (
          <span>
            {[row.original.first_name, row.original.last_name]
              .filter(Boolean)
              .join(' ') || row.original.username}
          </span>
        ),
      },
      {
        accessorKey: 'email',
        header: 'Email',
      },
      {
        accessorKey: 'phone_number',
        header: 'Phone',
        cell: ({ row }) => row.original.phone_number || '-',
      },
      {
        accessorKey: 'roles',
        header: 'Roles',
        enableSorting: false,
        cell: ({ row }) => (
          <div className="flex flex-wrap gap-1">
            {row.original.roles?.length ? (
              row.original.roles.map((role) => (
                <Badge key={role.id ?? role.name} variant="outline">
                  {role.display_name || role.name}
                </Badge>
              ))
            ) : (
              <span className="text-muted-foreground">-</span>
            )}
          </div>
        ),
      },
      {
        accessorKey: 'created_at',
        header: 'Created',
        cell: ({ row }) => formatDate(row.original.created_at),
      },
      {
        accessorKey: 'effective_status',
        header: 'Status',
        cell: ({ row }) => (
          <Badge
            variant={
              row.original.effective_status === 'active'
                ? 'default'
                : 'secondary'
            }
          >
            {row.original.effective_status}
          </Badge>
        ),
      },
    ];
  }, []);
}
