import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../../../../core/services/request_workflow_service.dart';

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _ink = Color(0xFF18241E);
const Color _muted = Color(0xFF68766F);
const Color _border = Color(0xFFE0E7E3);
const Color _surface = Color(0xFFF8FAF9);

class PendingRequestsSubTab extends StatefulWidget {
  final String adminName;
  final VoidCallback? onChanged;

  const PendingRequestsSubTab({
    super.key,
    required this.adminName,
    this.onChanged,
  });

  @override
  State<PendingRequestsSubTab> createState() => _PendingRequestsSubTabState();
}

class _PendingRequestsSubTabState extends State<PendingRequestsSubTab> {
  final _search = TextEditingController();
  List<Map<String, dynamic>> _requests = [];
  bool _loading = true;
  String? _error;
  String _filter = 'all';

  @override
  void initState() {
    super.initState();
    _load();
    _search.addListener(() => setState(() {}));
  }

  @override
  void dispose() {
    _search.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    if (mounted) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }
    try {
      final rows = await RequestWorkflowService.getRequests(scope: 'pending');
      if (!mounted) return;
      setState(() {
        _requests = rows;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = RequestWorkflowService.cleanError(e);
        _loading = false;
      });
    }
  }

  bool _bool(dynamic v) => v == true || v == 1 || v == '1' || v == 'true';

  List<Map<String, dynamic>> get _visible {
    final q = _search.text.trim().toLowerCase();
    return _requests.where((row) {
      final action = _bool(row['action_required']);
      final owner = _bool(row['is_owner']);
      if (_filter == 'action' && !action) return false;
      if (_filter == 'tracking' && !owner) return false;
      if (q.isEmpty) return true;
      final hay = [
        row['reference'], row['body'], row['requester_name'], row['recipient_position'],
        row['target_campus'], row['category'], row['priority'],
      ].map((e) => '${e ?? ''}'.toLowerCase()).join(' ');
      return hay.contains(q);
    }).toList();
  }

  int get _actionCount => _requests.where((e) => _bool(e['action_required'])).length;
  int get _trackingCount => _requests.where((e) => _bool(e['is_owner'])).length;

  Future<void> _open(Map<String, dynamic> request) async {
    final changed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => RequestWorkflowDetailDialog(request: request),
    );
    if (changed == true) {
      widget.onChanged?.call();
      await _load();
    }
  }

  void _snack(String text, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(text),
        backgroundColor: error ? Colors.red.shade700 : _green,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const Center(child: CircularProgressIndicator(color: _green));
    }
    if (_error != null) {
      return _RequestError(message: _error!, onRetry: _load);
    }

    return RefreshIndicator(
      onRefresh: _load,
      color: _green,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 650;
          final horizontal = constraints.maxWidth >= 1000 ? 28.0 : (compact ? 12.0 : 18.0);
          final list = _visible;

          return ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: EdgeInsets.fromLTRB(horizontal, 10, horizontal, 100),
            children: [
              _WorkspaceToolbar(
                compact: compact,
                search: _search,
                filter: _filter,
                actionCount: _actionCount,
                trackingCount: _trackingCount,
                onFilter: (value) => setState(() => _filter = value),
                onRefresh: _load,
              ),
              const SizedBox(height: 14),
              if (list.isEmpty)
                _EmptyWorkflow(
                  filter: _filter,
                  hasAny: _requests.isNotEmpty,
                )
              else
                ..._buildSections(list, compact),
            ],
          );
        },
      ),
    );
  }

  List<Widget> _buildSections(List<Map<String, dynamic>> list, bool compact) {
    final action = list.where((e) => _bool(e['action_required'])).toList();
    final tracking = list.where((e) => !_bool(e['action_required'])).toList();
    final widgets = <Widget>[];

    if (action.isNotEmpty) {
      widgets.add(_SectionHeading(
        icon: Icons.priority_high_rounded,
        title: 'ACTION REQUIRED',
        subtitle: 'Requests currently assigned to your position and campus',
        count: action.length,
        color: const Color(0xFFB43B33),
      ));
      widgets.add(const SizedBox(height: 9));
      widgets.addAll(action.map((r) => Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: _RequestCard(
              request: r,
              compact: compact,
              onOpen: () => _open(r),
              onCancel: null,
            ),
          )));
    }

    if (tracking.isNotEmpty) {
      if (widgets.isNotEmpty) widgets.add(const SizedBox(height: 14));
      widgets.add(_SectionHeading(
        icon: Icons.route_rounded,
        title: 'MY ROUTING TRACKER',
        subtitle: 'Requests you sent and are waiting on another office',
        count: tracking.length,
        color: _green,
      ));
      widgets.add(const SizedBox(height: 9));
      widgets.addAll(tracking.map((r) => Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: _RequestCard(
              request: r,
              compact: compact,
              onOpen: () => _open(r),
              onCancel: null,
            ),
          )));
    }
    return widgets;
  }
}

class _WorkspaceToolbar extends StatelessWidget {
  final bool compact;
  final TextEditingController search;
  final String filter;
  final int actionCount;
  final int trackingCount;
  final ValueChanged<String> onFilter;
  final VoidCallback onRefresh;

  const _WorkspaceToolbar({
    required this.compact,
    required this.search,
    required this.filter,
    required this.actionCount,
    required this.trackingCount,
    required this.onFilter,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(compact ? 13 : 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: _border),
      ),
      child: Column(
        children: [
          Row(
            children: [
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Active workflow', style: TextStyle(fontSize: 17, color: _ink, fontWeight: FontWeight.w900)),
                    SizedBox(height: 3),
                    Text('Review assigned work and track requests you have dispatched.', style: TextStyle(fontSize: 11.5, color: _muted)),
                  ],
                ),
              ),
              IconButton(onPressed: onRefresh, tooltip: 'Refresh', icon: const Icon(Icons.refresh_rounded, color: _green)),
            ],
          ),
          const SizedBox(height: 12),
          if (compact)
            Column(
              children: [
                _SearchBox(controller: search),
                const SizedBox(height: 10),
                SingleChildScrollView(scrollDirection: Axis.horizontal, child: _filters()),
              ],
            )
          else
            Row(
              children: [
                Expanded(child: _SearchBox(controller: search)),
                const SizedBox(width: 12),
                _filters(),
              ],
            ),
        ],
      ),
    );
  }

  Widget _filters() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        _FilterChip(label: 'All', selected: filter == 'all', onTap: () => onFilter('all')),
        const SizedBox(width: 7),
        _FilterChip(label: 'Action $actionCount', selected: filter == 'action', onTap: () => onFilter('action')),
        const SizedBox(width: 7),
        _FilterChip(label: 'Tracking $trackingCount', selected: filter == 'tracking', onTap: () => onFilter('tracking')),
      ],
    );
  }
}

class _SearchBox extends StatelessWidget {
  final TextEditingController controller;
  const _SearchBox({required this.controller});
  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: controller,
      decoration: InputDecoration(
        hintText: 'Search subject, office, campus or requester...',
        prefixIcon: const Icon(Icons.search_rounded, size: 20),
        suffixIcon: controller.text.isEmpty
            ? null
            : IconButton(onPressed: controller.clear, icon: const Icon(Icons.close_rounded, size: 18)),
        filled: true,
        fillColor: _surface,
        isDense: true,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _gold, width: 1.4)),
      ),
    );
  }
}

class _FilterChip extends StatelessWidget {
  final String label;
  final bool selected;
  final VoidCallback onTap;
  const _FilterChip({required this.label, required this.selected, required this.onTap});
  @override
  Widget build(BuildContext context) {
    return Material(
      color: selected ? _green : _surface,
      borderRadius: BorderRadius.circular(30),
      child: InkWell(
        borderRadius: BorderRadius.circular(30),
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
          child: Text(label, style: TextStyle(color: selected ? Colors.white : _muted, fontWeight: FontWeight.w800, fontSize: 11)),
        ),
      ),
    );
  }
}

class _SectionHeading extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final int count;
  final Color color;
  const _SectionHeading({required this.icon, required this.title, required this.subtitle, required this.count, required this.color});
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Container(width: 35, height: 35, decoration: BoxDecoration(color: color.withOpacity(0.08), borderRadius: BorderRadius.circular(10)), child: Icon(icon, color: color, size: 18)),
        const SizedBox(width: 10),
        Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(title, style: TextStyle(color: color, fontWeight: FontWeight.w900, fontSize: 11, letterSpacing: 0.8)), Text(subtitle, style: const TextStyle(color: _muted, fontSize: 10.5))])),
        Container(padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5), decoration: BoxDecoration(color: color.withOpacity(0.08), borderRadius: BorderRadius.circular(20)), child: Text('$count', style: TextStyle(color: color, fontWeight: FontWeight.w900, fontSize: 11))),
      ],
    );
  }
}

class _RequestCard extends StatelessWidget {
  final Map<String, dynamic> request;
  final bool compact;
  final VoidCallback onOpen;
  final VoidCallback? onCancel;

  const _RequestCard({required this.request, required this.compact, required this.onOpen, this.onCancel});

  String _date(dynamic raw) {
    try {
      return DateFormat('MMM d, yyyy • h:mm a').format(DateTime.parse('$raw').toLocal());
    } catch (_) {
      return '';
    }
  }

  bool _hasVisibleTable() {
    dynamic raw = request['table_data'];
    if (raw is String && raw.trim().isNotEmpty) {
      try {
        raw = jsonDecode(raw);
      } catch (_) {}
    }
    if (raw is Map) {
      final enabled = raw['enabled'];
      if (enabled == false || enabled == 0 || enabled == '0' || enabled == 'false') {
        return false;
      }
      final columns = raw['columns'];
      if (columns is List) return columns.isNotEmpty;
    }
    return request['has_table'] == true ||
        request['has_table'] == 1 ||
        request['has_table'] == '1';
  }

  @override
  Widget build(BuildContext context) {
    final action = request['action_required'] == true || request['action_required'] == 1 || request['action_required'] == '1';
    final priority = '${request['priority'] ?? 'normal'}'.toLowerCase();
    final priorityColor = priority == 'urgent' ? Colors.red.shade700 : priority == 'important' ? _gold : _green;
    final routeColor = action ? const Color(0xFFB43B33) : _green;

    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(15),
      child: InkWell(
        onTap: onOpen,
        borderRadius: BorderRadius.circular(15),
        child: Container(
          padding: EdgeInsets.all(compact ? 14 : 17),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(15), border: Border.all(color: action ? routeColor.withOpacity(0.28) : _border)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 42,
                    height: 42,
                    decoration: BoxDecoration(color: routeColor.withOpacity(0.08), borderRadius: BorderRadius.circular(12)),
                    child: Icon(action ? Icons.assignment_late_rounded : Icons.outbox_rounded, color: routeColor, size: 21),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('${request['reference'] ?? 'Untitled request'}', maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontSize: 14, fontWeight: FontWeight.w900)),
                        const SizedBox(height: 4),
                        Text(action ? 'From ${request['requester_name'] ?? 'Staff member'}' : 'Waiting at ${request['recipient_position'] ?? 'next office'}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 11.5, fontWeight: FontWeight.w600)),
                      ],
                    ),
                  ),
                  const SizedBox(width: 8),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
                    decoration: BoxDecoration(color: priorityColor.withOpacity(0.08), borderRadius: BorderRadius.circular(20)),
                    child: Text(priority.toUpperCase(), style: TextStyle(color: priorityColor, fontSize: 8.5, fontWeight: FontWeight.w900, letterSpacing: 0.5)),
                  ),
                ],
              ),
              const SizedBox(height: 13),
              Text('${request['body'] ?? ''}', maxLines: compact ? 2 : 3, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 12, height: 1.42)),
              const SizedBox(height: 13),
              Wrap(
                spacing: 7,
                runSpacing: 7,
                children: [
                  _Tag(icon: Icons.badge_outlined, text: '${request['recipient_position'] ?? ''}'),
                  _Tag(icon: Icons.location_on_outlined, text: '${request['target_campus'] ?? ''}'),
                  _Tag(icon: Icons.category_outlined, text: '${request['category'] ?? 'General'}'),
                  if (_hasVisibleTable())
                    const _Tag(icon: Icons.table_chart_outlined, text: 'Structured table'),
                ],
              ),
              const SizedBox(height: 13),
              Row(
                children: [
                  Icon(Icons.schedule_rounded, size: 14, color: Colors.grey.shade500),
                  const SizedBox(width: 5),
                  Expanded(child: Text(_date(request['updated_at'] ?? request['created_at']), style: const TextStyle(fontSize: 10.5, color: _muted, fontWeight: FontWeight.w600))),
                  if (onCancel != null)
                    TextButton(onPressed: onCancel, child: const Text('Cancel', style: TextStyle(color: Colors.redAccent, fontSize: 11, fontWeight: FontWeight.w800))),
                  const SizedBox(width: 5),
                  FilledButton.icon(
                    onPressed: onOpen,
                    style: FilledButton.styleFrom(backgroundColor: routeColor, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 9), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9))),
                    icon: Icon(action ? Icons.gavel_rounded : Icons.visibility_outlined, size: 15),
                    label: Text(action ? 'TAKE ACTION' : 'TRACK', style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w900)),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Tag extends StatelessWidget {
  final IconData icon;
  final String text;
  const _Tag({required this.icon, required this.text});
  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: const BoxConstraints(maxWidth: 260),
      padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 6),
      decoration: BoxDecoration(color: _surface, borderRadius: BorderRadius.circular(20), border: Border.all(color: _border)),
      child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 13, color: _green), const SizedBox(width: 5), Flexible(child: Text(text, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 9.5, color: _muted, fontWeight: FontWeight.w700)))]),
    );
  }
}

class _EmptyWorkflow extends StatelessWidget {
  final String filter;
  final bool hasAny;
  const _EmptyWorkflow({required this.filter, required this.hasAny});
  @override
  Widget build(BuildContext context) {
    final title = hasAny ? 'Nothing matches this filter' : 'Workflow is clear';
    final body = hasAny ? 'Change the filter or search terms to see other requests.' : 'There are no pending requests assigned to you and nothing currently awaiting action in your tracker.';
    return Container(
      margin: const EdgeInsets.only(top: 18),
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 52),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: _border)),
      child: Column(children: [Container(width: 68, height: 68, decoration: BoxDecoration(color: _green.withOpacity(0.06), shape: BoxShape.circle), child: const Icon(Icons.task_alt_rounded, color: _green, size: 34)), const SizedBox(height: 15), Text(title, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: _ink)), const SizedBox(height: 6), ConstrainedBox(constraints: const BoxConstraints(maxWidth: 520), child: Text(body, textAlign: TextAlign.center, style: const TextStyle(color: _muted, fontSize: 12, height: 1.45)))]),
    );
  }
}

class _RequestError extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _RequestError({required this.message, required this.onRetry});
  @override
  Widget build(BuildContext context) {
    return Center(child: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisSize: MainAxisSize.min, children: [Icon(Icons.cloud_off_rounded, size: 48, color: Colors.red.shade300), const SizedBox(height: 12), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _muted)), const SizedBox(height: 15), OutlinedButton.icon(onPressed: onRetry, icon: const Icon(Icons.refresh_rounded), label: const Text('Retry'))])));
  }
}

class RequestWorkflowDetailDialog extends StatefulWidget {
  final Map<String, dynamic> request;
  final bool readOnly;

  const RequestWorkflowDetailDialog({super.key, required this.request, this.readOnly = false});

  @override
  State<RequestWorkflowDetailDialog> createState() => _RequestWorkflowDetailDialogState();
}

class _RequestWorkflowDetailDialogState extends State<RequestWorkflowDetailDialog> {
  final _remarks = TextEditingController();
  final ScrollController _documentVerticalScroll = ScrollController();
  final ScrollController _routingVerticalScroll = ScrollController();
  final ScrollController _savedTableHorizontalScroll = ScrollController();
  final ScrollController _workflowHorizontalScroll = ScrollController();
  bool _working = false;

  bool _flag(String key) {
    final v = widget.request[key];
    return v == true || v == 1 || v == '1' || v == 'true';
  }

  bool get _actionRequired => !widget.readOnly && _flag('action_required');
  bool get _owner => _flag('is_owner');
  bool get _canApprove => _actionRequired && _flag('can_approve');
  bool get _canCancel => _actionRequired && _flag('can_cancel');
  bool get _canEscalate => _actionRequired && _flag('can_escalate');

  List<Map<String, dynamic>> get _nextRoutes {
    final raw = widget.request['next_routes'];
    if (raw is! List) return const [];
    return raw
        .whereType<Map>()
        .map((e) => e.map((key, value) => MapEntry(key.toString(), value)))
        .toList();
  }

  Map<String, dynamic>? get _nextRoute => _nextRoutes.isEmpty ? null : _nextRoutes.first;

  @override
  void dispose() {
    _remarks.dispose();
    _documentVerticalScroll.dispose();
    _routingVerticalScroll.dispose();
    _savedTableHorizontalScroll.dispose();
    _workflowHorizontalScroll.dispose();
    super.dispose();
  }

  Future<bool> _confirm({required String title, required String message, required String actionLabel, required Color color}) async {
    final value = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('GO BACK')),
          FilledButton(
            onPressed: () => Navigator.pop(ctx, true),
            style: FilledButton.styleFrom(backgroundColor: color, foregroundColor: Colors.white),
            child: Text(actionLabel),
          ),
        ],
      ),
    );
    return value == true;
  }

  Future<void> _act(String action) async {
    final id = int.tryParse('${widget.request['id'] ?? 0}') ?? 0;
    if (id <= 0) return;

    if (action == 'route' || action.startsWith('route_')) {
      final requestedStage = action.startsWith('route_')
          ? action.substring('route_'.length).trim().toLowerCase()
          : '';
      Map<String, dynamic>? route;
      if (requestedStage.isNotEmpty) {
        for (final candidate in _nextRoutes) {
          if ('${candidate['stage'] ?? ''}'.trim().toLowerCase() == requestedStage) {
            route = candidate;
            break;
          }
        }
      } else {
        route = _nextRoute;
      }

      final available = route != null &&
          (route['available'] == true || route['available'] == 1 || route['available'] == '1');
      if (!_canEscalate || !available) {
        final detail = (route?['detail'] ?? 'The selected routing office is not available.').toString();
        _snack(detail, error: true);
        return;
      }

      final destination = (route!['stage_label'] ?? route['position_title'] ?? 'the next office').toString();
      final campus = (route['campus'] ?? _routingCampusForNext(route)).toString();
      final ok = await _confirm(
        title: 'Route to $destination?',
        message: 'This request will be transferred to $destination at $campus. The receiving administrator will be notified immediately.',
        actionLabel: 'ROUTE REQUEST',
        color: _gold,
      );
      if (!ok) return;
    }

    if (action == 'approve') {
      final ok = await _confirm(
        title: 'Approve this request?',
        message: 'This closes the workflow as approved. The requester will be notified immediately.',
        actionLabel: 'APPROVE',
        color: _green,
      );
      if (!ok) return;
    }

    if (action == 'cancel') {
      final ok = await _confirm(
        title: 'Cancel this request?',
        message: 'Only the administrator currently responsible for the request can cancel it. This action closes the workflow and notifies the requester.',
        actionLabel: 'CANCEL REQUEST',
        color: Colors.red.shade700,
      );
      if (!ok) return;
    }

    setState(() => _working = true);
    try {
      await RequestWorkflowService.actOnRequest(
        requestId: id,
        action: action,
        remarks: _remarks.text,
      );
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      _snack(RequestWorkflowService.cleanError(e), error: true);
      setState(() => _working = false);
    }
  }

  void _snack(String text, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(text),
        backgroundColor: error ? Colors.red.shade700 : _green,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final compact = size.width < 760;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 7 : 24, vertical: compact ? 8 : 20),
      backgroundColor: Colors.transparent,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 1060, maxHeight: size.height * 0.95),
        child: Material(
          color: Colors.white,
          borderRadius: BorderRadius.circular(compact ? 14 : 18),
          clipBehavior: Clip.antiAlias,
          elevation: 14,
          child: Column(
            children: [
              _detailHeader(),
              Expanded(
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    final wide = constraints.maxWidth >= 840;
                    if (wide) {
                      return Row(
                        children: [
                          Expanded(flex: 6, child: _documentPane(compact: false)),
                          const VerticalDivider(width: 1, color: _border),
                          Expanded(flex: 4, child: _routingPane()),
                        ],
                      );
                    }
                    return DefaultTabController(
                      length: 2,
                      child: Column(
                        children: [
                          const Material(
                            color: Colors.white,
                            child: TabBar(
                              labelColor: _green,
                              unselectedLabelColor: _muted,
                              indicatorColor: _gold,
                              tabs: [Tab(text: 'REQUEST'), Tab(text: 'ROUTING')],
                            ),
                          ),
                          Expanded(child: TabBarView(children: [_documentPane(compact: true), _routingPane()])),
                        ],
                      ),
                    );
                  },
                ),
              ),
              if (_actionRequired) _actionBar(compact),
            ],
          ),
        ),
      ),
    );
  }

  Widget _detailHeader() {
    final priority = '${widget.request['priority'] ?? 'normal'}'.toUpperCase();
    final stage = '${widget.request['current_stage'] ?? ''}'.toUpperCase();
    return Container(
      padding: const EdgeInsets.fromLTRB(18, 13, 9, 13),
      decoration: const BoxDecoration(color: _green, border: Border(bottom: BorderSide(color: _gold, width: 3))),
      child: Row(
        children: [
          const Icon(Icons.description_rounded, color: Colors.white),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('${widget.request['reference'] ?? 'OFFICIAL REQUEST'}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 14)),
                const SizedBox(height: 2),
                Text('$priority • ${widget.request['category'] ?? 'General'}${stage.isEmpty ? '' : ' • $stage'}', style: const TextStyle(color: Color(0xFFE0F0E6), fontSize: 10.3, fontWeight: FontWeight.w700)),
              ],
            ),
          ),
          if (_actionRequired)
            Container(
              margin: const EdgeInsets.only(right: 4),
              padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
              decoration: BoxDecoration(color: _gold, borderRadius: BorderRadius.circular(20)),
              child: const Text('ADMIN ACTION', style: TextStyle(color: Colors.white, fontSize: 8.5, fontWeight: FontWeight.w900, letterSpacing: .5)),
            ),
          IconButton(onPressed: _working ? null : () => Navigator.pop(context), icon: const Icon(Icons.close_rounded, color: Colors.white)),
        ],
      ),
    );
  }

  Map<String, String> _campusInfo(String campus) {
    final clean = campus.trim().toUpperCase();
    if (clean.contains('MANSA')) return {'campus': 'Mansa Campus, Off Samfya Road, Mansa,', 'box': 'P.O Box 71000, Mansa.', 'phone': '+260 572 429 305', 'email': 'mansacampus@rockview.ac.zm'};
    if (clean.contains('NDOLA')) return {'campus': 'Ndola Campus, Kansenshi, Ndola,', 'box': 'P.O Box 71111, Ndola.', 'phone': '+260 572 429 305', 'email': 'ndolacampus@rockview.ac.zm'};
    if (clean.contains('CHIPATA')) return {'campus': 'Chipata Campus, Great East Road, Chipata,', 'box': 'P.O Box 51000, Chipata.', 'phone': '+260 572 429 305', 'email': 'chipatacampus@rockview.ac.zm'};
    if (clean.contains('LIVINGSTONE')) return {'campus': 'Livingstone Campus, Mosi-O-Tunya Road, Livingstone,', 'box': 'P.O Box 61000, Livingstone.', 'phone': '+260 572 429 305', 'email': 'livingstonecampus@rockview.ac.zm'};
    if (clean.contains('E-LEARNING') || clean.contains('ELEARNING') || clean.contains('ONLINE')) return {'campus': 'E-Learning Campus,Online, Rockview University,', 'box': 'P.O Box 31108, Lusaka.', 'phone': '+260 572 429 305', 'email': 'elearning@rockview.ac.zm'};
    if (clean.contains('10 MILES') || clean.contains('TEN MILES')) return {'campus': '10 Miles Campus, Off Mungule Road, Chibombo,', 'box': 'P.O Box 31108, Lusaka.', 'phone': '+260 572 429 305', 'email': '10milescampus@rockview.ac.zm'};
    return {'campus': 'Head Quarters,Off Mungule Road,Chibombo,Lusaka,', 'box': 'P.O Box 31108, Lusaka.', 'phone': '+260 572 429 305', 'email': 'hq@rockview.ac.zm'};
  }

  String _formalDate(dynamic raw) {
    try {
      final date = DateTime.parse('$raw').toLocal();
      final month = DateFormat('MMMM').format(date).toUpperCase();
      final day = date.day;
      String suffix = 'TH';
      if (day % 100 < 11 || day % 100 > 13) {
        if (day % 10 == 1) suffix = 'ST';
        if (day % 10 == 2) suffix = 'ND';
        if (day % 10 == 3) suffix = 'RD';
      }
      return '${day.toString().padLeft(2, '0')}$suffix $month, ${date.year}';
    } catch (_) {
      return '$raw';
    }
  }

  Map<String, dynamic>? _savedTableData() {
    final raw = widget.request['table_data'];
    if (raw is Map) {
      return raw.map((key, value) => MapEntry(key.toString(), value));
    }
    if (raw is String && raw.trim().isNotEmpty) {
      try {
        final decoded = jsonDecode(raw);
        if (decoded is Map) {
          return decoded.map((key, value) => MapEntry(key.toString(), value));
        }
      } catch (_) {}
    }
    return null;
  }

  Widget _documentPane({required bool compact}) {
    final campus = '${widget.request['requester_campus'] ?? widget.request['target_campus'] ?? ''}';
    final info = _campusInfo(campus);
    final requester = '${widget.request['requester_name'] ?? 'Staff member'}';
    final requesterPosition = '${widget.request['requester_position'] ?? 'Staff'}';
    final table = _savedTableData();
    final requesterDepartment = () {
      for (final value in [
        widget.request['requester_department'],
        widget.request['sender_department'],
        widget.request['requester_program'],
        widget.request['program'],
        table?['department_snapshot'],
      ]) {
        final text = '${value ?? ''}'.trim();
        if (text.isNotEmpty && text.toLowerCase() != 'null') return text;
      }
      return '';
    }();
    final serif = TextStyle(
      fontFamily: 'Times New Roman',
      fontSize: compact ? 12.4 : 13.8,
      height: 1.55,
      color: const Color(0xFF202020),
    );
    final serifBold = serif.copyWith(fontWeight: FontWeight.bold);
    final greenStrip = compact ? 8.0 : 28.0;
    final goldStrip = compact ? 17.0 : 54.0;

    return ColoredBox(
      color: const Color(0xFFF0F3F1),
      child: ListView(
        controller: _documentVerticalScroll,
        primary: false,
        cacheExtent: 500,
        padding: EdgeInsets.all(compact ? 6 : 14),
        children: [
          Center(
            child: Container(
              constraints: const BoxConstraints(maxWidth: 850, minHeight: 930),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: _border),
                boxShadow: [BoxShadow(color: Colors.black.withOpacity(.075), blurRadius: 22, offset: const Offset(0, 9))],
              ),
              child: Stack(
                children: [
                  Positioned.fill(
                    child: IgnorePointer(
                      child: Center(
                        child: Opacity(
                          opacity: .035,
                          child: Image.asset(
                            'assets/logo.png',
                            width: compact ? 260 : 430,
                            fit: BoxFit.contain,
                            errorBuilder: (_, __, ___) => const SizedBox.shrink(),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Positioned(left: 0, top: 0, bottom: 0, child: Container(width: greenStrip, color: _green)),
                  Positioned(
                    left: greenStrip,
                    top: compact ? 44 : 48,
                    child: ClipPath(
                      clipper: _DetailGoldRibbonClipper(),
                      child: Container(width: goldStrip, height: compact ? 265 : 520, color: const Color(0xFFF2A500)),
                    ),
                  ),
                  Positioned(
                    left: greenStrip,
                    top: compact ? 296 : 540,
                    child: ClipPath(
                      clipper: _DetailBlackPointerClipper(),
                      child: Container(width: goldStrip, height: compact ? 27 : 45, color: Colors.black),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(compact ? 28 : 96, compact ? 20 : 18, compact ? 18 : 54, compact ? 52 : 70),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Center(
                          child: Column(
                            children: [
                              Image.asset(
                                'assets/logo.png',
                                height: compact ? 58 : 84,
                                errorBuilder: (_, __, ___) => const Icon(Icons.school, color: _green, size: 70),
                              ),
                              SizedBox(height: compact ? 7 : 9),
                              FittedBox(
                                fit: BoxFit.scaleDown,
                                child: Text(
                                  'ROCKVIEW UNIVERSITY',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: 'Times New Roman',
                                    color: const Color(0xFF00A52A),
                                    fontSize: compact ? 24 : 40,
                                    fontWeight: FontWeight.w900,
                                    letterSpacing: .5,
                                  ),
                                ),
                              ),
                              Text(
                                '${info['campus']} ${info['box']}',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.7 : 10.3, fontWeight: FontWeight.bold, height: 1.18),
                              ),
                              Text(
                                'Office line:  ${info['phone']}',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.7 : 10, fontWeight: FontWeight.bold),
                              ),
                              const SizedBox(height: 4),
                              Wrap(
                                alignment: WrapAlignment.center,
                                crossAxisAlignment: WrapCrossAlignment.center,
                                spacing: 4,
                                children: [
                                  Text('Web site:', style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.4 : 9.7, fontWeight: FontWeight.bold)),
                                  Text('www.rockviewuniversity.ac', style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.4 : 9.7, color: Colors.blue.shade700, decoration: TextDecoration.underline)),
                                  Text('Email:', style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.4 : 9.7, fontWeight: FontWeight.bold)),
                                  Text('${info['email']}', style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.4 : 9.7, color: Colors.blue.shade700, decoration: TextDecoration.underline)),
                                ],
                              ),
                              const SizedBox(height: 7),
                              Text(
                                'All correspondences must be directed to the office of the Chief Executive Officer and not to individual officers by name',
                                textAlign: TextAlign.center,
                                style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 8.1 : 9.5),
                              ),
                              const SizedBox(height: 10),
                              Container(height: 2, color: const Color(0xFF00A05A)),
                            ],
                          ),
                        ),
                        SizedBox(height: compact ? 22 : 28),
                        _docRow('TO:', '${widget.request['recipient_position'] ?? ''}'.toUpperCase(), serifBold),
                        const SizedBox(height: 9),
                        _docRow('FROM:', '${requester.toUpperCase()} - ${requesterPosition.toUpperCase()}', serifBold),
                        const SizedBox(height: 9),
                        _docRow('DATE:', _formalDate(widget.request['created_at']), serif),
                        SizedBox(height: compact ? 18 : 23),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(width: 50, child: Text('RE:', style: serifBold)),
                            Expanded(child: SelectableText('${widget.request['reference'] ?? ''}'.toUpperCase(), style: serifBold)),
                          ],
                        ),
                        const SizedBox(height: 24),
                        SelectableText('${widget.request['body'] ?? ''}', style: serif),
                        if (table != null && table['columns'] is List) ...[
                          const SizedBox(height: 15),
                          _buildSavedRequestTable(table, compact: compact, serif: serif, serifBold: serifBold),
                        ],
                        const SizedBox(height: 24),
                        Text('Yours Faithfully,', style: serif),
                        const SizedBox(height: 8),
                        Transform(
                          transform: Matrix4.skewX(-.15),
                          child: Text(
                            requester,
                            style: TextStyle(
                              fontFamily: 'Brush Script MT',
                              fontFamilyFallback: const ['Dancing Script', 'Caveat', 'Pacifico', 'cursive'],
                              fontSize: compact ? 29 : 36,
                              color: const Color(0xFF345CC4),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Text(requester, style: serif),
                        const SizedBox(height: 3),
                        Text(requesterPosition, style: serifBold.copyWith(decoration: TextDecoration.underline)),
                        const SizedBox(height: 3),
                        if (requesterDepartment.isNotEmpty)
                          Text(
                            'Department: $requesterDepartment',
                            style: serif.copyWith(
                              fontWeight: FontWeight.w600,
                              color: _muted,
                            ),
                          ),
                        if (_owner && !_actionRequired && !widget.readOnly) ...[
                          const SizedBox(height: 22),
                          Container(
                            padding: const EdgeInsets.all(11),
                            decoration: BoxDecoration(
                              color: _gold.withOpacity(.055),
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(color: _gold.withOpacity(.20)),
                            ),
                            child: const Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Icon(Icons.visibility_outlined, color: _gold, size: 17),
                                SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    'Tracking view only. Staff/requesters cannot approve, escalate or cancel requests. Only the administrator at the current routing position can act.',
                                    style: TextStyle(color: _muted, fontSize: 10.3, height: 1.38, fontWeight: FontWeight.w600),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                        const SizedBox(height: 24),
                      ],
                    ),
                  ),
                  Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
                    child: Container(
                      height: compact ? 31 : 46,
                      color: _green,
                      alignment: Alignment.center,
                      child: Text(
                        '“ PROFICIENCY AND EXCELLENCE ”',
                        style: TextStyle(color: Colors.white, fontSize: compact ? 8.8 : 11.5, fontWeight: FontWeight.bold, letterSpacing: compact ? 1.5 : 2.5),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSavedRequestTable(
    Map<String, dynamic> table, {
    required bool compact,
    required TextStyle serif,
    required TextStyle serifBold,
  }) {
    final columnsRaw = table['columns'];
    final rowsRaw = table['rows'];
    if (columnsRaw is! List || columnsRaw.isEmpty) return const SizedBox.shrink();

    final columns = <Map<String, dynamic>>[];
    for (final raw in columnsRaw) {
      if (raw is Map) {
        columns.add(raw.map((key, value) => MapEntry(key.toString(), value)));
      } else {
        columns.add(<String, dynamic>{'label': '$raw', 'width': 140});
      }
    }

    final rows = <List<dynamic>>[];
    if (rowsRaw is List) {
      for (final raw in rowsRaw) {
        if (raw is Map && raw['cells'] is List) {
          rows.add(List<dynamic>.from(raw['cells'] as List));
        } else if (raw is List) {
          rows.add(List<dynamic>.from(raw));
        }
      }
    }

    final widths = columns.map((column) {
      final parsed = double.tryParse('${column['width'] ?? 140}') ?? 140;
      return parsed.clamp(80.0, 360.0).toDouble();
    }).toList();
    final totalWidth = widths.fold<double>(0, (sum, width) => sum + width);
    final title = '${table['title'] ?? 'Table description'}'.trim();
    const grid = Color(0xFFD8E1DC);
    const headerFill = Color(0xFFF2F7F4);
    const alternateRow = Color(0xFFFBFCFB);

    return LayoutBuilder(
      builder: (context, constraints) {
        final viewportWidth = constraints.maxWidth.isFinite ? constraints.maxWidth : totalWidth;
        final contentWidth = totalWidth < viewportWidth ? viewportWidth : totalWidth;
        final needsScroll = totalWidth > viewportWidth + 1;

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    title.isEmpty ? 'Table description' : title,
                    style: serifBold.copyWith(fontSize: compact ? 11.3 : 12.2),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4),
                  decoration: BoxDecoration(
                    color: _green.withOpacity(.06),
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(color: _green.withOpacity(.13)),
                  ),
                  child: const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.table_chart_outlined, size: 12, color: _green),
                      SizedBox(width: 4),
                      Text('STRUCTURED TABLE', style: TextStyle(color: _green, fontSize: 7.8, fontWeight: FontWeight.w900, letterSpacing: .35)),
                    ],
                  ),
                ),
              ],
            ),
            if (needsScroll) ...[
              const SizedBox(height: 5),
              const Row(
                children: [
                  Icon(Icons.swap_horiz_rounded, size: 13, color: _muted),
                  SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      'Scroll horizontally inside the table to view all columns.',
                      style: TextStyle(color: _muted, fontSize: 8.7, fontWeight: FontWeight.w600),
                    ),
                  ),
                ],
              ),
            ],
            const SizedBox(height: 7),
            Container(
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(9),
                border: Border.all(color: grid),
              ),
              clipBehavior: Clip.antiAlias,
              child: Scrollbar(
                controller: _savedTableHorizontalScroll,
                thumbVisibility: needsScroll,
                trackVisibility: needsScroll,
                interactive: true,
                scrollbarOrientation: ScrollbarOrientation.bottom,
                child: SingleChildScrollView(
                  controller: _savedTableHorizontalScroll,
                  scrollDirection: Axis.horizontal,
                  physics: const ClampingScrollPhysics(),
                  padding: EdgeInsets.only(bottom: needsScroll ? 10 : 0),
                  child: SizedBox(
                    width: contentWidth,
                    child: Column(
                      children: [
                        SizedBox(
                          height: compact ? 42 : 46,
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: List.generate(columns.length, (index) {
                              return Container(
                                width: widths[index],
                                alignment: Alignment.centerLeft,
                                padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
                                decoration: const BoxDecoration(
                                  color: headerFill,
                                  border: Border(
                                    right: BorderSide(color: grid),
                                    bottom: BorderSide(color: grid),
                                  ),
                                ),
                                child: Text(
                                  '${columns[index]['label'] ?? ''}'.toUpperCase(),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: serifBold.copyWith(
                                    fontFamily: 'Arial',
                                    fontSize: compact ? 9.2 : 10.1,
                                    color: _ink,
                                    letterSpacing: .15,
                                    height: 1.15,
                                  ),
                                ),
                              );
                            }),
                          ),
                        ),
                        ...List.generate(rows.length, (rowIndex) {
                          final row = rows[rowIndex];
                          final rowColor = rowIndex.isOdd ? alternateRow : Colors.white;
                          return SizedBox(
                            height: compact ? 46 : 50,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: List.generate(columns.length, (index) {
                                final value = index < row.length ? '${row[index] ?? ''}' : '';
                                return Container(
                                  width: widths[index],
                                  alignment: Alignment.centerLeft,
                                  padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
                                  decoration: BoxDecoration(
                                    color: rowColor,
                                    border: const Border(
                                      right: BorderSide(color: grid),
                                      bottom: BorderSide(color: grid),
                                    ),
                                  ),
                                  child: Text(
                                    value,
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                    style: serif.copyWith(
                                      fontFamily: 'Arial',
                                      fontSize: compact ? 9.4 : 10.3,
                                      height: 1.25,
                                      color: _ink,
                                    ),
                                  ),
                                );
                              }),
                            ),
                          );
                        }),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _docRow(String label, String value, TextStyle style) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(width: 50, child: Text(label, style: style.copyWith(fontWeight: FontWeight.bold))),
        Expanded(child: SelectableText(value, style: style)),
      ],
    );
  }

  String _originCampus() {
    final value = '${widget.request['requester_campus'] ?? widget.request['origin_campus'] ?? widget.request['target_campus'] ?? ''}'.trim();
    return value.isEmpty ? 'Origin Campus' : value;
  }

  bool _isHeadquartersStage(String raw) {
    final value = raw.trim().toLowerCase();
    return value.contains('dvc1') ||
        value.contains('deputy vice') ||
        value.contains('accountant') ||
        value.contains('cfo') ||
        value.contains('chief financial') ||
        value.contains('ceo') ||
        value.contains('chief executive');
  }

  String _routingCampusForStage(String stage) {
    return _isHeadquartersStage(stage) ? 'HQ CAMPUS' : _originCampus();
  }

  String _routingCampusForNext(Map<String, dynamic>? route) {
    if (route == null) return '';
    final descriptor = [
      route['stage'],
      route['stage_key'],
      route['stage_label'],
      route['position_title'],
    ].map((e) => '${e ?? ''}').join(' ');
    return _routingCampusForStage(descriptor);
  }

  Widget _routingPane() {
    final historyRaw = widget.request['history'];
    final history = historyRaw is List
        ? historyRaw.whereType<Map>().map((e) => e.map((k, v) => MapEntry(k.toString(), v))).toList()
        : <Map<String, dynamic>>[];
    return ColoredBox(
      color: _surface,
      child: ListView(
        controller: _routingVerticalScroll,
        primary: false,
        cacheExtent: 400,
        padding: const EdgeInsets.all(20),
        children: [
          const Text('ROUTING HISTORY', style: TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 14)),
          const SizedBox(height: 4),
          const Text('The backend records every authenticated hand-off and final decision.', style: TextStyle(color: _muted, fontSize: 11)),
          const SizedBox(height: 18),
          if (history.isEmpty)
            const Text('No routing events are available yet.', style: TextStyle(color: _muted))
          else
            ...List.generate(history.length, (index) => _RouteTimelineNode(event: history[index], isLast: index == history.length - 1)),
          const SizedBox(height: 12),
          _workflowChain(),
          if (_actionRequired) ...[
            const SizedBox(height: 14),
            Container(
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(13), border: Border.all(color: _border)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Row(children: [Icon(Icons.verified_user_outlined, color: _green, size: 19), SizedBox(width: 8), Text('Your administrator position is the current action point', style: TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 11.5))]),
                  const SizedBox(height: 6),
                  Text('Current office: ${widget.request['recipient_position']} • ${_routingCampusForStage('${widget.request['current_stage'] ?? widget.request['recipient_position'] ?? ''}')}. Registrar is campus-specific; DVC1, Accountant, CFO and CEO are institutional HQ CAMPUS offices.', style: const TextStyle(color: _muted, fontSize: 10.8, height: 1.4)),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _workflowChain() {
    final steps = <Map<String, String>>[
      {'label': 'STAFF', 'scope': 'ORIGIN'},
      {'label': 'REGISTRAR', 'scope': 'CAMPUS'},
      {'label': 'DVC1', 'scope': 'HQ'},
      {'label': 'ACCOUNTANT', 'scope': 'HQ'},
      {'label': 'CFO', 'scope': 'HQ'},
      {'label': 'CEO', 'scope': 'HQ'},
    ];
    final stage = '${widget.request['current_stage'] ?? ''}'.toLowerCase();
    var activeIndex = 0;
    if (stage == 'registrar') activeIndex = 1;
    if (stage == 'dvc1') activeIndex = 2;
    if (stage == 'accountant') activeIndex = 3;
    if (stage == 'cfo') activeIndex = 4;
    if (stage == 'ceo') activeIndex = 5;

    Widget node(Map<String, String> step, int index) {
      final active = index == activeIndex;
      final decision = index == 2
          ? 'ACCOUNTANT OR CFO'
          : index == 4
              ? 'CEO OPTIONAL'
              : '';
      return Container(
        width: 92,
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
        decoration: BoxDecoration(
          color: active ? _green.withOpacity(.09) : _surface,
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: active ? _green.withOpacity(.35) : _border),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              step['label']!,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 8.9,
                fontWeight: FontWeight.w900,
                color: active ? _green : _ink,
              ),
            ),
            const SizedBox(height: 2),
            Text(
              step['scope']!,
              style: TextStyle(
                fontSize: 7.4,
                fontWeight: FontWeight.w900,
                color: active ? _green : _muted,
                letterSpacing: .35,
              ),
            ),
            if (decision.isNotEmpty) ...[
              const SizedBox(height: 5),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                decoration: BoxDecoration(
                  color: _gold.withOpacity(.10),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: _gold.withOpacity(.25)),
                ),
                child: Text(
                  decision,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    fontSize: 6.4,
                    fontWeight: FontWeight.w900,
                    color: _gold,
                    letterSpacing: .15,
                  ),
                ),
              ),
            ],
          ],
        ),
      );
    }

    return Container(
      padding: const EdgeInsets.all(13),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(Icons.account_tree_outlined, size: 16, color: _green),
              SizedBox(width: 7),
              Text(
                'CONTROLLED APPROVAL ROUTE',
                style: TextStyle(fontSize: 9.5, fontWeight: FontWeight.w900, color: _muted, letterSpacing: .7),
              ),
            ],
          ),
          const SizedBox(height: 5),
          Text(
            'Campus Registrar: ${_originCampus()}  •  Central approvals: HQ CAMPUS',
            style: const TextStyle(fontSize: 9.5, color: _ink, fontWeight: FontWeight.w700),
          ),
          const SizedBox(height: 10),
          Scrollbar(
            controller: _workflowHorizontalScroll,
            thumbVisibility: true,
            trackVisibility: true,
            scrollbarOrientation: ScrollbarOrientation.bottom,
            thickness: 5,
            radius: const Radius.circular(10),
            child: SingleChildScrollView(
              controller: _workflowHorizontalScroll,
              scrollDirection: Axis.horizontal,
              primary: false,
              padding: const EdgeInsets.only(bottom: 14),
              child: Row(
                children: List.generate(steps.length, (i) {
                  return Row(
                    children: [
                      node(steps[i], i),
                      if (i < steps.length - 1)
                        const Padding(
                          padding: EdgeInsets.symmetric(horizontal: 6),
                          child: Icon(Icons.arrow_forward_rounded, size: 15, color: _gold),
                        ),
                    ],
                  );
                }),
              ),
            ),
          ),
          const SizedBox(height: 7),
          const Text(
            'Routing policy: Registrar always sends to DVC1 at Head Quarters. DVC1 may send the request to the Accountant or route it directly to the CFO. The Accountant routes to the CFO. The CFO may return it to the Accountant, approve it, or escalate it to the CEO. CEO is an optional final executive stage.',
            style: TextStyle(color: _muted, fontSize: 9.6, height: 1.45),
          ),
        ],
      ),
    );
  }

  String _routeButtonLabel(Map<String, dynamic> route) {
    final stage = '${route['stage'] ?? ''}'.trim().toLowerCase();
    final current = '${widget.request['current_stage'] ?? ''}'.trim().toLowerCase();
    final label = (route['stage_label'] ?? route['position_title'] ?? 'Next Office').toString().toUpperCase();
    if (current == 'dvc1' && stage == 'cfo') return 'ROUTE DIRECT TO CFO';
    if (current == 'cfo' && stage == 'accountant') return 'RETURN TO ACCOUNTANT';
    if (current == 'cfo' && stage == 'ceo') return 'ROUTE TO CEO';
    return 'ROUTE TO $label';
  }

  bool _routeAvailable(Map<String, dynamic> route) {
    final value = route['available'];
    return value == true || value == 1 || value == '1' || value == 'true';
  }

  Widget _actionBar(bool compact) {
    final routes = _nextRoutes;
    final availableCount = routes.where(_routeAvailable).length;

    return Container(
      padding: EdgeInsets.fromLTRB(compact ? 11 : 18, 11, compact ? 11 : 18, 13),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: _border)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextField(
            controller: _remarks,
            minLines: 1,
            maxLines: 3,
            decoration: InputDecoration(
              hintText: 'Add official remarks, justification or processing note...',
              prefixIcon: const Icon(Icons.edit_note_rounded, color: _green),
              filled: true,
              fillColor: _surface,
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: _border)),
              enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: _border)),
              focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: _gold, width: 1.4)),
            ),
          ),
          const SizedBox(height: 9),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 9),
            decoration: BoxDecoration(
              color: _gold.withOpacity(.055),
              borderRadius: BorderRadius.circular(9),
              border: Border.all(color: _gold.withOpacity(.18)),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Icon(Icons.alt_route_rounded, color: _gold, size: 18),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    routes.isEmpty
                        ? 'No further routing office is configured from this stage. You may approve or cancel the request.'
                        : availableCount > 0
                            ? 'Select the appropriate routing destination below. Only offices with an active HQ CAMPUS assignment can receive the request.'
                            : 'The permitted next office(s) are not currently assigned. Configure the required Head Quarters office holder before routing.',
                    style: const TextStyle(color: _muted, fontSize: 10.5, height: 1.35, fontWeight: FontWeight.w600),
                  ),
                ),
              ],
            ),
          ),
          if (routes.any((r) => !_routeAvailable(r))) ...[
            const SizedBox(height: 7),
            ...routes.where((r) => !_routeAvailable(r)).map(
              (route) => Padding(
                padding: const EdgeInsets.only(bottom: 4),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Icon(Icons.info_outline_rounded, size: 14, color: Colors.orange.shade700),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Text(
                        '${route['stage_label'] ?? route['position_title'] ?? 'Office'}: ${route['detail'] ?? 'No active administrator assignment.'}',
                        style: TextStyle(color: Colors.orange.shade900, fontSize: 9.6, height: 1.3),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
          const SizedBox(height: 9),
          _actionButtons(compact),
        ],
      ),
    );
  }

  Widget _actionButtons(bool compact) {
    final buttons = <Widget>[];

    buttons.add(
      OutlinedButton.icon(
        onPressed: _working || !_canCancel ? null : () => _act('cancel'),
        style: OutlinedButton.styleFrom(
          foregroundColor: Colors.red.shade700,
          side: BorderSide(color: Colors.red.shade200),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
        ),
        icon: const Icon(Icons.block_rounded, size: 16),
        label: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 9.5)),
      ),
    );

    for (final route in _nextRoutes) {
      final stage = '${route['stage'] ?? ''}'.trim().toLowerCase();
      final available = _routeAvailable(route);
      buttons.add(
        FilledButton.icon(
          onPressed: _working || !_canEscalate || !available || stage.isEmpty
              ? null
              : () => _act('route_$stage'),
          style: FilledButton.styleFrom(
            backgroundColor: stage == 'ceo' ? _green : _gold,
            foregroundColor: Colors.white,
            disabledBackgroundColor: _border,
            disabledForegroundColor: _muted,
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
          ),
          icon: Icon(stage == 'ceo' ? Icons.account_balance_rounded : Icons.alt_route_rounded, size: 16),
          label: Text(
            _routeButtonLabel(route),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 9.2),
          ),
        ),
      );
    }

    buttons.add(
      FilledButton.icon(
        onPressed: _working || !_canApprove ? null : () => _act('approve'),
        style: FilledButton.styleFrom(
          backgroundColor: _green,
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
        ),
        icon: _working
            ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
            : const Icon(Icons.verified_rounded, size: 16),
        label: const Text('APPROVE', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 9.5)),
      ),
    );

    if (compact) {
      return Column(
        children: buttons
            .map((b) => Padding(
                  padding: const EdgeInsets.only(bottom: 6),
                  child: SizedBox(width: double.infinity, child: b),
                ))
            .toList(),
      );
    }

    return Align(
      alignment: Alignment.centerLeft,
      child: Wrap(
        spacing: 7,
        runSpacing: 7,
        children: buttons.map((b) => ConstrainedBox(constraints: const BoxConstraints(minWidth: 150), child: b)).toList(),
      ),
    );
  }

}


class _DetailGoldRibbonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.moveTo(0, 0);
    path.lineTo(size.width, size.height * .055);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height * .92);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}

class _DetailBlackPointerClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.moveTo(0, 0);
    path.lineTo(size.width, size.height * .35);
    path.lineTo(0, size.height);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}

class _RouteBanner extends StatelessWidget {
  final String from;
  final String to;
  final String campus;
  const _RouteBanner({required this.from, required this.to, required this.campus});
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(color: _surface, borderRadius: BorderRadius.circular(13), border: Border.all(color: _border)),
      child: Row(children: [Expanded(child: _RoutePoint(label: 'FROM', value: from, icon: Icons.person_outline_rounded)), const Padding(padding: EdgeInsets.symmetric(horizontal: 8), child: Icon(Icons.arrow_forward_rounded, color: _gold, size: 20)), Expanded(child: _RoutePoint(label: 'CURRENT DESK', value: to, icon: Icons.badge_outlined)), const SizedBox(width: 8), Tooltip(message: campus, child: const Icon(Icons.location_on_rounded, color: _green, size: 18))]),
    );
  }
}

class _RoutePoint extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  const _RoutePoint({required this.label, required this.value, required this.icon});
  @override
  Widget build(BuildContext context) {
    return Row(children: [Icon(icon, color: _green, size: 18), const SizedBox(width: 7), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(label, style: const TextStyle(color: _muted, fontSize: 8.5, fontWeight: FontWeight.w900, letterSpacing: 0.6)), Text(value, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontSize: 10.5, fontWeight: FontWeight.w800))]))]);
  }
}

class _RouteTimelineNode extends StatelessWidget {
  final Map<String, dynamic> event;
  final bool isLast;
  const _RouteTimelineNode({required this.event, required this.isLast});

  String _time(dynamic raw) {
    try { return DateFormat('MMM d, yyyy • h:mm a').format(DateTime.parse('$raw').toLocal()); } catch (_) { return ''; }
  }

  @override
  Widget build(BuildContext context) {
    final action = '${event['action'] ?? 'updated'}'.toLowerCase();
    Color color = _green;
    IconData icon = Icons.check_circle_outline_rounded;
    if (action == 'routed') { color = _gold; icon = Icons.alt_route_rounded; }
    if (action == 'declined' || action == 'cancelled') { color = Colors.red.shade700; icon = Icons.cancel_outlined; }
    if (action == 'submitted') { color = const Color(0xFF245A88); icon = Icons.outbox_rounded; }

    final to = '${event['to_position'] ?? ''}'.trim();
    final toCampus = '${event['to_campus'] ?? ''}'.trim();
    final remarks = '${event['remarks'] ?? ''}'.trim();
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(children: [Container(width: 34, height: 34, decoration: BoxDecoration(color: color.withOpacity(0.08), shape: BoxShape.circle, border: Border.all(color: color.withOpacity(0.25))), child: Icon(icon, color: color, size: 17)), if (!isLast) Container(width: 2, height: 48, color: color.withOpacity(0.18))]),
        const SizedBox(width: 11),
        Expanded(child: Padding(padding: const EdgeInsets.only(top: 2, bottom: 14), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [Expanded(child: Text(action.toUpperCase(), style: TextStyle(color: color, fontWeight: FontWeight.w900, fontSize: 10.5, letterSpacing: 0.5))), Text(_time(event['created_at']), style: const TextStyle(color: _muted, fontSize: 9))]), const SizedBox(height: 3), Text('${event['actor_name'] ?? 'System'} • ${event['actor_position'] ?? ''}', style: const TextStyle(color: _ink, fontWeight: FontWeight.w700, fontSize: 10.5)), if (to.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 3), child: Text('To $to${toCampus.isEmpty ? '' : ' • $toCampus'}', style: const TextStyle(color: _muted, fontSize: 10))), if (remarks.isNotEmpty) Padding(padding: const EdgeInsets.only(top: 3), child: Text(remarks, style: const TextStyle(color: _muted, fontSize: 10, fontStyle: FontStyle.italic)))]))),
      ],
    );
  }
}
