'use client';

import { useEffect } from 'react';
import {
  AdminTable,
  type ActionDef,
  type BulkActionDef,
  type ColumnDef,
} from '@/components/ui/domain/admin/AdminTable';
import type { UserRow } from './UsersMgmt';
import { userDisplayLabel } from './usersMgmt.shared';

interface UsersMgmtTableProps {
  tableWrapRef: React.RefObject<HTMLDivElement | null>;
  columns: ColumnDef<UserRow>[];
  data: UserRow[];
  isInitialLoading: boolean;
  actions: ActionDef<UserRow>[];
  selectedIds: string[];
  setSelectedIds: (ids: string[]) => void;
  bulkActions: BulkActionDef[];
  bulkSelectedLabel: string;
  bulkClearLabel: string;
  selectAllLabel: string;
  rowSelectLabel: string;
  highlightedIndex: number;
  isLoading: boolean;
}

export function UsersMgmtTable({
  tableWrapRef,
  columns,
  data,
  isInitialLoading,
  actions,
  selectedIds,
  setSelectedIds,
  bulkActions,
  bulkSelectedLabel,
  bulkClearLabel,
  selectAllLabel,
  rowSelectLabel,
  highlightedIndex,
  isLoading,
}: UsersMgmtTableProps) {
  const activeHighlight =
    data.length === 0 || highlightedIndex < 0 ? -1 : Math.min(highlightedIndex, data.length - 1);

  useEffect(() => {
    const wrap = tableWrapRef.current;
    if (!wrap) return;
    const rows = wrap.querySelectorAll('tbody tr');
    rows.forEach((row, idx) => {
      row.classList.toggle('bg-brand-primary-50', idx === activeHighlight);
      row.classList.toggle('ring-1', idx === activeHighlight);
      row.classList.toggle('ring-brand-primary-300', idx === activeHighlight);
    });
  }, [activeHighlight, data, isLoading, tableWrapRef]);

  return (
    <div ref={tableWrapRef}>
      <AdminTable<UserRow>
        columns={columns}
        rows={data}
        loading={isInitialLoading}
        virtualize={{
          estimateRowHeight: 56,
          scrollRestorationKey: '/admin/users',
          scrollRestorationReady: !isInitialLoading && data.length > 0,
        }}
        rowHref={(r) => `/admin/users/${r.id}`}
        actions={actions}
        selectable
        selectedIds={selectedIds}
        onSelectionChange={setSelectedIds}
        bulkActions={bulkActions}
        bulkSelectedLabel={bulkSelectedLabel}
        bulkClearLabel={bulkClearLabel}
        selectAllLabel={selectAllLabel}
        rowSelectLabel={(row) => `${rowSelectLabel} ${userDisplayLabel(row)}`}
      />
    </div>
  );
}
