# Admin Settings Frontend Implementation Plan

## Audience & Scope
- **Intended executor**: AI agent implementing MotoVaultPro admin settings UI across desktop and mobile.
- **Scope**: Frontend-only tasks within `frontend/`, coordinating with existing backend admin APIs. Includes real-time audit log integration and bulk operations across admin users, catalog entities, and station management.

## Current State Summary
- Routes exist (`frontend/src/pages/admin/*.tsx`, `frontend/src/features/admin/mobile/*.tsx`) but contain placeholder copy.
- Hooks and API clients (`frontend/src/features/admin/hooks/*`, `frontend/src/features/admin/api/admin.api.ts`) already wrap CRUD endpoints but lack bulk helpers and streaming.
- Settings pages link into admin routes; `useAdminAccess` gate is wired.
- No shared admin layout, tables, or selection utilities; no real-time audit consumption; no bulk UI.

## Key Requirements
1. **Real-time audit logging** for admin operations (desktop + mobile).
2. **Bulk operations**: multi-select + batch mutate/delete/revoke across admin users, catalog hierarchy, stations.
3. **Desktop / Mobile parity** while respecting CLAUDE.md mobile + desktop mandate and existing design system.

Assumptions:
- Backend will expose streaming endpoint (`/api/admin/audit-logs/stream`) using SSE. (If absent, coordinate for addition.)
- Backend will provide/extend batch mutation endpoints or accept arrays in current ones.
- No additional design assets; follow existing Material UI / GlassCard patterns.

## Implementation Phases

### Phase 0 – Prep & Validation
- Confirm backend endpoints:
  - `GET /api/admin/audit-logs/stream` (SSE) payload schema.
  - Batch endpoints for admins (`POST /admin/admins/bulk`, `PATCH /admin/admins/bulk-revoke`, etc.), catalog (`/admin/catalog/{entity}/bulk-delete`), stations (`/admin/stations/bulk-delete`).
  - Response format + error contracts.
- Document agreements in `docs/ADMIN.md` and update API client typings before UI work.

### Phase 1 – Shared Infrastructure
- Add shared admin components under `frontend/src/features/admin/components/`:
  - `AdminSectionHeader`
  - `AdminDataGrid` (wrapper around MUI DataGrid or Table) with checkbox selection and toolbar slot.
  - `SelectionToolbar` + `BulkActionDialog`.
  - `AuditLogPanel` (desktop) and `AuditLogDrawer` (mobile).
  - `EmptyState`, `ErrorState`, `Skeleton` variants.
- Utility hooks/services:
  - `useBulkSelection` (manages item selection, select all, reset).
  - `useAuditLogStream` (SSE handling, merge into cache, pause/resume).
  - `useAdminRealtimeEffect` (common real-time logic for both platforms).
  - Error normalization helper for API responses.
- Update `admin.api.ts` to include bulk endpoints and streaming subscription helper.
  - Ensure types in `admin.types.ts` cover new request/response payloads.

### Phase 2 – Admin Users Experience
- **Desktop (`AdminUsersPage.tsx`)**:
  - Replace placeholder with layout:
    - Header (stats summary cards).
    - `AdminDataGrid` listing admins (columns: email, role, status, created/updated, last activity).
    - Toolbar actions: Invite, Revoke, Reinstate, Delete (single + bulk), export CSV placeholder.
    - Inline filters/search.
    - Audit log side panel fed by `useAuditLogStream`.
  - Modals/forms:
    - Invite admin (react-hook-form + Zod validation).
    - Confirm dialogs for revoke/reinstate/delete (bulk friendly).
  - State management:
    - Use React Query hooks (`useAdmins`, new `useBulkRevokeAdmins`, etc.).
    - Optimistic updates where safe; fallback to refetch on failure.
    - Surface backend constraints (last admin protection) in toasts/dialogs.
- **Mobile (`AdminUsersMobileScreen.tsx`)**:
  - Card-based list with segmented controls.
  - Multi-select mode triggered by long-press or “Select” button; sticky bottom action bar for bulk operations.
  - Slide-in drawer for audit log stream; allow collapse to preserve screen space.
  - Ensure loading/error/empty states match mobile pattern.

### Phase 3 – Vehicle Catalog Management
- Extend API hooks for per-entity bulk operations (`useDeleteMakesBulk`, etc.) and streaming updates.
- **Desktop (`AdminCatalogPage.tsx`)**:
  - Two-column layout: left panel shows hierarchical tree (Makes → Models → Years → Trims → Engines). Right panel shows detail grid for selected level.
  - Support multi-select in each grid with bulk delete; confirm cascading impacts (warn when deleting parents).
  - Modals for create/edit per entity using shared form component (with validation & parent context).
  - Audit log panel filtered to catalog-related actions.
  - Show breadcrumbs + context metadata (created/updated timestamps).
- **Mobile (`AdminCatalogMobileScreen.tsx`)**:
  - Drill-down navigation (list of makes → models → ...).
  - Selection mode toggles for bulk delete at current depth; use bottom sheet to display actions.
  - Provide “Recent Changes” sheet consuming audit stream (filtered).
- Handle cache invalidation across hierarchies (e.g., deleting a make invalidates models/years/trims queries). Consider using queryClient `invalidateQueries` with partial keys.

### Phase 4 – Station Oversight
- Hook updates: add `useBulkDeleteStations`, `useBulkRestoreStations` if available, with optional `force` flag.
- **Desktop (`AdminStationsPage.tsx`)**:
  - Data grid with columns (name, address, status, last modified, createdBy). Add search bar and filter chips (active, soft-deleted).
  - Bulk selection with delete (soft/hard toggle), restore, export stub.
  - Station detail drawer with metadata and quick actions.
  - Audit log panel focusing on station events; highlight critical operations via toast (e.g., hard deletes).
- **Mobile (`AdminStationsMobileScreen.tsx`)**:
  - Card list with quick actions (edit, delete, restore). Multi-select mode with sticky action bar.
  - Provide filter tabs (All / Active / Deleted).
  - Integrate audit log bottom sheet.

### Phase 5 – Integration & Routing Enhancements
- Introduce route wrapper/components (e.g., `AdminUsersRoute`) that detect viewport using `useMediaQuery` and render desktop or mobile variant; ensures shared logic and prevents duplicate routing code.
- Update navigation flows, ensuring mobile bottom navigation can reach admin sections gracefully.
- Document keyboard shortcuts or focus management for accessibility (bulk selection, audit log toggles).

### Phase 6 – Testing & QA
- Add unit tests for new hooks (`useAuditLogStream`, bulk hooks) using Jest + Testing Library. Mock EventSource for streaming tests.
- Component tests:
  - Desktop grids: selection toggles, bulk action dialogs, form validation.
  - Mobile screens: selection mode toggling, action bar behaviors.
  - Audit log panels: streaming update rendering, pause/resume controls.
- Visual regression smoke tests if tooling available; otherwise document manual screenshot checkpoints.
- Manual QA matrix:
  - Desktop ≥1280px and mobile ≤480px.
  - Test flows: invite admin, revoke/reinstate, bulk revoke, catalog cascading delete, station soft/hard delete, audit log live updates.

## Deliverables Checklist
- [ ] Updated API client + types for batch + streaming.
- [ ] Shared admin UI components & utilities.
- [ ] Desktop admin pages fully functional with bulk + real-time features.
- [ ] Mobile admin screens matching functionality.
- [ ] Comprehensive tests covering new flows.
- [ ] Documentation updates (API usage, manual QA steps).

## Risks & Mitigations
- **Streaming availability**: If backend stream not ready, fall back to polling with progressive enhancement; keep SSE integration behind feature flag.
- **Bulk API inconsistencies**: Align payload format with backend; add defensive UI (disable actions until backend confirms support).
- **State synchronization**: Ensure query invalidation covers dependent entities; consider structured query keys and `queryClient.setQueryData` for incremental updates.
- **Mobile UX complexity**: Prototype selection mode early to validate ergonomics; leverage bottom sheets to avoid cramped toolbars.

## Follow-up Questions (Resolved)
1. Real-time audit logs required — implement SSE-based stream handling.
2. Bulk operations mandatory — support multi-select + batch actions across admin users, catalog entities, stations.
3. No additional design constraints — rely on existing Material UI and GlassCard paradigms.

## Handoff Notes
- Keep code comments concise per developer guidelines; avoid introducing new design systems.
- Validate hooks for Auth0 dependency (ensure disabled when unauthenticated).
- Coordinate with backend team if API gaps found; document interim shims.
- Maintain responsiveness and accessibility; ensure touch targets ≥44px and keyboard operability on desktop grids.

