'use client';

import { Badge } from '@/components/ui/badge';
import { DataTable } from '@/components/ui/table/data-table';
import { DataTableColumnHeader } from '@/components/ui/table/data-table-column-header';
import { DataTableToolbar } from '@/components/ui/table/data-table-toolbar';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { useSuspenseQuery } from '@tanstack/react-query';
import type { Column, ColumnDef } from '@tanstack/react-table';
import type { User } from '@/features/users/api/types';
import { ROLE_OPTIONS } from '@/features/users/components/users-table/options';
import { Icons } from '@/components/icons';
import { exampleUsersQueryOptions } from '@/features/example-dashboard/api';

const columns: ColumnDef<User>[] = [
  {
    accessorKey: 'name',
    header: ({ column }: { column: Column<User, unknown> }) => (
      <DataTableColumnHeader column={column} title='Name' />
    ),
    cell: ({ row }) => (
      <div className='flex flex-col'>
        <span className='font-medium'>{row.original.name}</span>
        <span className='text-muted-foreground text-xs'>{row.original.email}</span>
      </div>
    ),
    meta: {
      label: 'Name',
      placeholder: 'Search users...',
      variant: 'text' as const,
      icon: Icons.text
    },
    enableColumnFilter: true
  },
  {
    id: 'role',
    accessorFn: (row) =>
      row.systemRole === 'super_admin' ? 'super_admin' : row.activeMembershipRole ?? 'user',
    header: ({ column }: { column: Column<User, unknown> }) => (
      <DataTableColumnHeader column={column} title='Role' />
    ),
    cell: ({ row }) => {
      const role =
        row.original.systemRole === 'super_admin' ? 'super_admin' : row.original.activeMembershipRole;

      return (
        <Badge variant={role === 'admin' ? 'default' : 'outline'} className='capitalize'>
          {role?.replace('_', ' ') ?? 'user'}
        </Badge>
      );
    },
    enableColumnFilter: true,
    meta: {
      label: 'roles',
      variant: 'multiSelect' as const,
      options: ROLE_OPTIONS
    }
  },
  {
    id: 'organizations',
    accessorFn: (row) => row.organizations.map((organization) => organization.name).join(', '),
    header: ({ column }: { column: Column<User, unknown> }) => (
      <DataTableColumnHeader column={column} title='Organizations' />
    ),
    cell: ({ row }) => (
      <div className='flex flex-wrap gap-1'>
        {row.original.memberships.map((membership) => (
          <Badge key={membership.organizationId} variant='secondary'>
            {membership.organizationName} ({membership.membershipRole}, {membership.businessRole.replace('_', ' ')})
          </Badge>
        ))}
      </div>
    )
  }
];

const columnIds = columns.map((c) => c.id).filter(Boolean) as string[];

export function ExampleUserTable() {
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    role: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.name && { search: params.name }),
    ...(params.role && { roles: params.role }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
  };

  const { data } = useSuspenseQuery(exampleUsersQueryOptions(filters));
  const pageCount = Math.ceil(data.total_users / params.perPage);

  const { table } = useDataTable({
    data: data.users,
    columns,
    pageCount,
    shallow: true
  });

  return (
    <DataTable table={table}>
      <DataTableToolbar table={table} />
    </DataTable>
  );
}
