import { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { StatCard, Tabs } from '@cameleer/design-system';
import { useRbacStats } from '../../api/queries/admin/rbac';
import styles from './UserManagement.module.css';
import UsersTab from './UsersTab';
import GroupsTab from './GroupsTab';
import RolesTab from './RolesTab';

const TABS = [
  { label: 'Users', value: 'users' },
  { label: 'Groups', value: 'groups' },
  { label: 'Roles', value: 'roles' },
];

const VALID_TABS = new Set(TABS.map((t) => t.value));

export default function RbacPage() {
  const { data: stats } = useRbacStats();
  const location = useLocation();
  const navigate = useNavigate();
  const [tab, setTab] = useState('users');
  const [highlightId, setHighlightId] = useState<string | null>(null);

  // Read tab + highlight from location state (set by cmd-k navigation)
  useEffect(() => {
    const state = location.state as { tab?: string; highlight?: string } | null;
    if (!state) return;

    if (state.tab && VALID_TABS.has(state.tab)) {
      setTab(state.tab);
    }
    if (state.highlight) {
      setHighlightId(state.highlight);
    }

    // Consume the state so back-navigation doesn't re-trigger
    navigate(location.pathname, { replace: true, state: null });
  }, [location.state]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div>
      <div className={styles.statStrip}>
        <StatCard label="Users" value={stats?.userCount ?? 0} />
        <StatCard label="Groups" value={stats?.groupCount ?? 0} />
        <StatCard label="Roles" value={stats?.roleCount ?? 0} />
      </div>
      <Tabs tabs={TABS} active={tab} onChange={(v) => { setTab(v); setHighlightId(null); }} />
      <div className={styles.tabContent}>
        {tab === 'users' && <UsersTab highlightId={highlightId} onHighlightConsumed={() => setHighlightId(null)} />}
        {tab === 'groups' && <GroupsTab highlightId={highlightId} onHighlightConsumed={() => setHighlightId(null)} />}
        {tab === 'roles' && <RolesTab highlightId={highlightId} onHighlightConsumed={() => setHighlightId(null)} />}
      </div>
    </div>
  );
}
