import 'dart:async';

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

import '../../../../core/models/user.dart';
import '../../../../core/networks/api_client.dart';
import '../../../../core/services/database_service.dart';
import '../../../../core/services/request_workflow_service.dart';
import 'pending_requests_sub_tab.dart';
import 'processed_requests_sub_tab.dart';
import 'routing_directory_sub_tab.dart';

const Color _requestGreen = Color.fromARGB(255, 2, 105, 48);
const Color _requestGold = Color.fromARGB(255, 204, 117, 4);
const Color _requestInk = Color(0xFF18241E);
const Color _requestMuted = Color(0xFF66736C);
const Color _requestBg = Color(0xFFF3F6F4);
const Color _requestBorder = Color(0xFFE0E7E3);

class RequestsMainTab extends StatefulWidget {
  final LocalUser? currentUser;

  const RequestsMainTab({super.key, this.currentUser});

  @override
  State<RequestsMainTab> createState() => _RequestsMainTabState();
}

class _RequestsMainTabState extends State<RequestsMainTab> {
  LocalUser? _user;
  int _index = 0;
  bool _loadingUser = true;
  bool _loadingSummary = true;
  Map<String, dynamic> _summary = const {};
  Timer? _summaryTimer;

  @override
  void initState() {
    super.initState();
    _loadUser();
    _refreshSummary();
    _summaryTimer = Timer.periodic(
      const Duration(seconds: 15),
      (_) => _refreshSummary(silent: true),
    );
  }

  @override
  void didUpdateWidget(covariant RequestsMainTab oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.currentUser != widget.currentUser && widget.currentUser != null) {
      setState(() => _user = widget.currentUser);
      _refreshSummary(silent: true);
    }
  }

  @override
  void dispose() {
    _summaryTimer?.cancel();
    super.dispose();
  }

  Future<void> _loadUser() async {
    final local = widget.currentUser ?? await DatabaseService.getLocalUser();
    if (!mounted) return;
    setState(() {
      _user = local;
      _loadingUser = false;
    });
  }

  Future<void> _refreshSummary({bool silent = false}) async {
    if (!silent && mounted) setState(() => _loadingSummary = true);
    try {
      final data = await RequestWorkflowService.getSummary();
      if (!mounted) return;
      setState(() {
        _summary = data;
        _loadingSummary = false;
        if (!_isAdmin && _index == 2) _index = 0;
      });
    } catch (_) {
      if (!mounted) return;
      setState(() => _loadingSummary = false);
    }
  }

  int _count(String key) => int.tryParse('${_summary[key] ?? 0}') ?? 0;

  // Active workflow contains requests currently waiting for this user as well
  // as requests submitted by this user that are still moving through routing.
  // Keeping both counts visible means a route never appears to disappear.
  int get _activeWorkflowCount =>
      _count('action_required_count') + _count('tracking_count');

  String get _displayName {
    final value = (_user?.fullName ?? '').trim();
    return value.isEmpty ? 'Rockview Staff' : value;
  }

  Map<String, dynamic> get _serverUser {
    final raw = _summary['current_user'];
    if (raw is Map) return raw.map((key, value) => MapEntry(key.toString(), value));
    return const <String, dynamic>{};
  }

  bool get _isAdmin {
    final value = _summary['is_admin'] ?? _serverUser['is_admin'];
    return value == true || value == 1 || value == '1' || value == 'true';
  }

  String get _campus {
    final server = (_serverUser['campus'] ?? '').toString().trim();
    if (server.isNotEmpty && server.toLowerCase() != 'null') return server;
    final value = (_user?.campus ?? '').trim();
    return value.isEmpty ? 'Campus not assigned' : value;
  }

  String get _position {
    final server = (_serverUser['position'] ?? '').toString().trim();
    if (server.isNotEmpty && server.toLowerCase() != 'null') return server;
    final value = (_user?.position ?? '').trim();
    if (value.isNotEmpty) return value;
    final role = (_user?.role ?? '').trim();
    return role.isEmpty ? 'Staff' : role;
  }

  String get _department {
    // The users table does not have a department column. Staff creation stores
    // the selected Departments-directory name in users.program.
    for (final key in const ['department_name', 'program']) {
      final value = (_serverUser[key] ?? '').toString().trim();
      if (value.isNotEmpty && value.toLowerCase() != 'null') return value;
    }
    return '';
  }

  Future<void> _openNewRequest() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _CreateRequestDialog(
        userName: _displayName,
        positionHint: _position,
        departmentHint: _department,
        campusHint: _campus == 'Campus not assigned' ? '' : _campus,
      ),
    );
    if (result == true) {
      setState(() => _index = 0);
      await _refreshSummary();
    }
  }

  Future<void> _openNotifications() async {
    await showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (_) => _RequestNotificationsDialog(
        onOpenRequest: (requestId) {
          _openRequestFromNotification(requestId);
        },
      ),
    );
    await _refreshSummary(silent: true);
  }

  Future<void> _openRequestFromNotification(int requestId) async {
    if (requestId <= 0) return;
    try {
      final request = await RequestWorkflowService.getRequest(requestId);
      if (!mounted) return;
      final status = '${request['status'] ?? 'pending'}'.toLowerCase();
      setState(() => _index = status == 'pending' ? 0 : 1);
      final changed = await showDialog<bool>(
        context: context,
        barrierDismissible: true,
        builder: (_) => RequestWorkflowDetailDialog(
          request: request,
          readOnly: status != 'pending',
        ),
      );
      if (changed == true) await _refreshSummary();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(RequestWorkflowService.cleanError(e)),
          backgroundColor: Colors.red.shade700,
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  Widget _currentBody() {
    if (_index == 1) {
      return ProcessedRequestsSubTab(
        key: const ValueKey('processed_requests'),
        adminName: _displayName,
        onChanged: () => _refreshSummary(silent: true),
      );
    }
    if (_index == 2 && _isAdmin) {
      return RoutingDirectorySubTab(
        key: const ValueKey('routing_directory'),
        onChanged: () => _refreshSummary(silent: true),
      );
    }
    return PendingRequestsSubTab(
      key: const ValueKey('pending_requests'),
      adminName: _displayName,
      onChanged: () => _refreshSummary(silent: true),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loadingUser) {
      return const ColoredBox(
        color: _requestBg,
        child: Center(child: CircularProgressIndicator(color: _requestGreen)),
      );
    }

    return Scaffold(
      backgroundColor: _requestBg,
      floatingActionButton: LayoutBuilder(
        builder: (context, constraints) {
          final compact = MediaQuery.sizeOf(context).width < 720;
          return compact
              ? FloatingActionButton(
                  onPressed: _openNewRequest,
                  backgroundColor: _requestGold,
                  foregroundColor: Colors.white,
                  tooltip: 'New request',
                  child: const Icon(Icons.add_rounded),
                )
              : const SizedBox.shrink();
        },
      ),
      bottomNavigationBar: MediaQuery.sizeOf(context).width < 860
          ? NavigationBar(
              selectedIndex: _index,
              backgroundColor: Colors.white,
              indicatorColor: _requestGreen.withOpacity(0.10),
              onDestinationSelected: (value) => setState(() => _index = value),
              destinations: [
                NavigationDestination(
                  icon: _BadgeIcon(
                    icon: Icons.inbox_outlined,
                    count: _activeWorkflowCount,
                  ),
                  selectedIcon: _BadgeIcon(
                    icon: Icons.inbox_rounded,
                    count: _activeWorkflowCount,
                  ),
                  label: 'Active',
                ),
                NavigationDestination(
                  icon: _BadgeIcon(
                    icon: Icons.inventory_2_outlined,
                    count: _count('processed_count'),
                  ),
                  selectedIcon: _BadgeIcon(
                    icon: Icons.inventory_2_rounded,
                    count: _count('processed_count'),
                  ),
                  label: 'Processed',
                ),
                if (_isAdmin)
                  const NavigationDestination(
                    icon: Icon(Icons.badge_outlined),
                    selectedIcon: Icon(Icons.badge_rounded),
                    label: 'Directory',
                  ),
              ],
            )
          : null,
      body: SafeArea(
        child: LayoutBuilder(
          builder: (context, constraints) {
            final desktop = constraints.maxWidth >= 1100;
            final tablet = constraints.maxWidth >= 860;

            final content = Column(
              children: [
                _Header(
                  compact: constraints.maxWidth < 650,
                  name: _displayName,
                  position: _position,
                  campus: _campus,
                  unreadNotifications: _count('unread_notifications'),
                  loadingSummary: _loadingSummary,
                  onNotifications: _openNotifications,
                  onNewRequest: _openNewRequest,
                  onRefresh: () => _refreshSummary(),
                ),
                _SummaryStrip(
                  compact: constraints.maxWidth < 650,
                  actionCount: _count('action_required_count'),
                  trackingCount: _count('tracking_count'),
                  processedCount: _count('processed_count'),
                ),
                Expanded(
                  child: AnimatedSwitcher(
                    duration: const Duration(milliseconds: 220),
                    child: _currentBody(),
                  ),
                ),
              ],
            );

            if (!tablet) return content;

            return Row(
              children: [
                _DesktopRail(
                  wide: desktop,
                  selectedIndex: _index,
                  activeCount: _activeWorkflowCount,
                  processedCount: _count('processed_count'),
                  showDirectory: _isAdmin,
                  onSelected: (value) => setState(() => _index = value),
                ),
                const VerticalDivider(width: 1, color: _requestBorder),
                Expanded(child: content),
              ],
            );
          },
        ),
      ),
    );
  }
}

class _DesktopRail extends StatelessWidget {
  final bool wide;
  final int selectedIndex;
  final int activeCount;
  final int processedCount;
  final bool showDirectory;
  final ValueChanged<int> onSelected;

  const _DesktopRail({
    required this.wide,
    required this.selectedIndex,
    required this.activeCount,
    required this.processedCount,
    required this.showDirectory,
    required this.onSelected,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: wide ? 230 : 82,
      color: Colors.white,
      child: Column(
        children: [
          const SizedBox(height: 20),
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: _requestGreen,
              borderRadius: BorderRadius.circular(14),
            ),
            child: const Icon(Icons.alt_route_rounded, color: Colors.white),
          ),
          if (wide) ...[
            const SizedBox(height: 10),
            const Text(
              'REQUEST ROUTING',
              style: TextStyle(
                color: _requestGreen,
                fontWeight: FontWeight.w900,
                fontSize: 12,
                letterSpacing: 0.9,
              ),
            ),
          ],
          const SizedBox(height: 26),
          _RailItem(
            wide: wide,
            selected: selectedIndex == 0,
            icon: Icons.inbox_rounded,
            label: 'Active workflow',
            count: activeCount,
            onTap: () => onSelected(0),
          ),
          _RailItem(
            wide: wide,
            selected: selectedIndex == 1,
            icon: Icons.inventory_2_rounded,
            label: 'Processed archive',
            count: processedCount,
            onTap: () => onSelected(1),
          ),
          if (showDirectory)
            _RailItem(
              wide: wide,
              selected: selectedIndex == 2,
              icon: Icons.badge_rounded,
              label: 'Routing directory',
              onTap: () => onSelected(2),
            ),
          const Spacer(),
          Padding(
            padding: const EdgeInsets.all(12),
            child: Tooltip(
              message: 'Routes are controlled by campus and database position',
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: _requestGreen.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.verified_user_outlined, color: _requestGreen, size: 18),
                    if (wide) ...[
                      const SizedBox(width: 8),
                      const Expanded(
                        child: Text(
                          'Authenticated routing',
                          style: TextStyle(fontSize: 11, color: _requestMuted, fontWeight: FontWeight.w700),
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _RailItem extends StatelessWidget {
  final bool wide;
  final bool selected;
  final IconData icon;
  final String label;
  final int count;
  final VoidCallback onTap;

  const _RailItem({
    required this.wide,
    required this.selected,
    required this.icon,
    required this.label,
    required this.onTap,
    this.count = 0,
  });

  @override
  Widget build(BuildContext context) {
    final fg = selected ? _requestGreen : _requestMuted;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      child: Material(
        color: selected ? _requestGreen.withOpacity(0.08) : Colors.transparent,
        borderRadius: BorderRadius.circular(12),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: onTap,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: wide ? 14 : 12, vertical: 13),
            child: Row(
              mainAxisAlignment: wide ? MainAxisAlignment.start : MainAxisAlignment.center,
              children: [
                _BadgeIcon(icon: icon, count: count),
                if (wide) ...[
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      label,
                      style: TextStyle(color: fg, fontWeight: FontWeight.w800, fontSize: 13),
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class _Header extends StatelessWidget {
  final bool compact;
  final String name;
  final String position;
  final String campus;
  final int unreadNotifications;
  final bool loadingSummary;
  final VoidCallback onNotifications;
  final VoidCallback onNewRequest;
  final VoidCallback onRefresh;

  const _Header({
    required this.compact,
    required this.name,
    required this.position,
    required this.campus,
    required this.unreadNotifications,
    required this.loadingSummary,
    required this.onNotifications,
    required this.onNewRequest,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(compact ? 14 : 24, 15, compact ? 10 : 20, 14),
      child: Row(
        children: [
          Container(
            width: compact ? 40 : 46,
            height: compact ? 40 : 46,
            decoration: BoxDecoration(
              color: _requestGreen.withOpacity(0.08),
              borderRadius: BorderRadius.circular(13),
            ),
            child: const Icon(Icons.account_tree_rounded, color: _requestGreen),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  compact ? 'Official Requests' : 'Official Request Routing',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: _requestInk,
                    fontWeight: FontWeight.w900,
                    fontSize: compact ? 17 : 21,
                  ),
                ),
                const SizedBox(height: 3),
                Text(
                  '$name • $position • $campus',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(color: _requestMuted, fontSize: 11.5, fontWeight: FontWeight.w600),
                ),
              ],
            ),
          ),
          if (!compact)
            IconButton(
              onPressed: loadingSummary ? null : onRefresh,
              tooltip: 'Refresh workflow',
              icon: loadingSummary
                  ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: _requestGreen))
                  : const Icon(Icons.refresh_rounded),
            ),
          IconButton(
            onPressed: onNotifications,
            tooltip: 'Workflow notifications',
            icon: _BadgeIcon(icon: Icons.notifications_none_rounded, count: unreadNotifications),
          ),
          if (!compact) ...[
            const SizedBox(width: 8),
            FilledButton.icon(
              onPressed: onNewRequest,
              style: FilledButton.styleFrom(
                backgroundColor: _requestGold,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              ),
              icon: const Icon(Icons.add_rounded, size: 18),
              label: const Text('NEW REQUEST', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 12)),
            ),
          ],
        ],
      ),
    );
  }
}

class _SummaryStrip extends StatelessWidget {
  final bool compact;
  final int actionCount;
  final int trackingCount;
  final int processedCount;

  const _SummaryStrip({
    required this.compact,
    required this.actionCount,
    required this.trackingCount,
    required this.processedCount,
  });

  @override
  Widget build(BuildContext context) {
    final cards = [
      _Metric(icon: Icons.assignment_late_outlined, label: 'NEEDS YOUR ACTION', value: actionCount, color: const Color(0xFFB53A32)),
      _Metric(icon: Icons.route_outlined, label: 'YOU ARE TRACKING', value: trackingCount, color: _requestGold),
      _Metric(icon: Icons.verified_outlined, label: 'PROCESSED', value: processedCount, color: _requestGreen),
    ];

    return Container(
      color: _requestBg,
      padding: EdgeInsets.fromLTRB(compact ? 12 : 20, 14, compact ? 12 : 20, 8),
      child: compact
          ? SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(children: cards.map((e) => Padding(padding: const EdgeInsets.only(right: 9), child: SizedBox(width: 168, child: e))).toList()),
            )
          : Row(children: cards.map((e) => Expanded(child: Padding(padding: const EdgeInsets.only(right: 10), child: e))).toList()),
    );
  }
}

class _Metric extends StatelessWidget {
  final IconData icon;
  final String label;
  final int value;
  final Color color;

  const _Metric({required this.icon, required this.label, required this.value, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: _requestBorder),
      ),
      child: Row(
        children: [
          Container(
            width: 38,
            height: 38,
            decoration: BoxDecoration(color: color.withOpacity(0.09), borderRadius: BorderRadius.circular(10)),
            child: Icon(icon, color: color, size: 20),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('$value', style: const TextStyle(fontSize: 19, fontWeight: FontWeight.w900, color: _requestInk)),
                Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 9.5, fontWeight: FontWeight.w800, color: _requestMuted, letterSpacing: 0.3)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _BadgeIcon extends StatelessWidget {
  final IconData icon;
  final int count;

  const _BadgeIcon({required this.icon, this.count = 0});

  @override
  Widget build(BuildContext context) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Icon(icon, color: _requestGreen),
        if (count > 0)
          Positioned(
            right: -9,
            top: -8,
            child: Container(
              constraints: const BoxConstraints(minWidth: 17, minHeight: 17),
              padding: const EdgeInsets.symmetric(horizontal: 4),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: const Color(0xFFB3261E),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.white, width: 1.5),
              ),
              child: Text(
                count > 99 ? '99+' : '$count',
                style: const TextStyle(color: Colors.white, fontSize: 8.5, fontWeight: FontWeight.w900),
              ),
            ),
          ),
      ],
    );
  }
}

class _CreateRequestDialog extends StatefulWidget {
  final String userName;
  final String positionHint;
  final String departmentHint;
  final String campusHint;

  const _CreateRequestDialog({
    required this.userName,
    required this.positionHint,
    this.departmentHint = '',
    required this.campusHint,
  });

  @override
  State<_CreateRequestDialog> createState() => _CreateRequestDialogState();
}

class _CreateRequestDialogState extends State<_CreateRequestDialog> {
  final _formKey = GlobalKey<FormState>();
  final _subject = TextEditingController();
  final _body = TextEditingController();
  final _amount = TextEditingController();
  final _tableTitle = TextEditingController(text: 'Table description');
  final ScrollController _workspaceScroll = ScrollController();
  final ScrollController _tableHorizontalScroll = ScrollController();
  final GlobalKey _tableSectionKey = GlobalKey();

  bool _loading = true;
  bool _submitting = false;
  bool _tableEnabled = false;
  String? _error;
  Map<String, dynamic> _directory = const {};
  String _resolvedDepartment = '';
  String? _departmentIssue;
  String _priority = 'normal';
  String _category = 'General';

  final List<_RequestTableColumnDraft> _tableColumns = <_RequestTableColumnDraft>[];
  final List<List<TextEditingController>> _tableRows = <List<TextEditingController>>[];

  static const _categories = <String>[
    'General',
    'Academic',
    'Human Resources',
    'Finance',
    'Procurement',
    'ICT',
    'Facilities',
    'Student Affairs',
    'Administration',
    'Other',
  ];

  @override
  void initState() {
    super.initState();
    _resetTableDraft();
    _loadRoutingContext();
  }

  @override
  void dispose() {
    _subject.dispose();
    _body.dispose();
    _amount.dispose();
    _tableTitle.dispose();
    _workspaceScroll.dispose();
    _tableHorizontalScroll.dispose();
    _disposeTableDraft();
    super.dispose();
  }

  void _disposeTableDraft() {
    for (final column in _tableColumns) {
      column.label.dispose();
    }
    for (final row in _tableRows) {
      for (final cell in row) {
        cell.dispose();
      }
    }
  }

  void _resetTableDraft() {
    _disposeTableDraft();
    _tableColumns
      ..clear()
      ..addAll([
        _RequestTableColumnDraft(label: 'QTY', width: 100),
        _RequestTableColumnDraft(label: 'DESCRIPTION', width: 260),
        _RequestTableColumnDraft(label: 'UNIT PRICE', width: 145),
        _RequestTableColumnDraft(label: 'AMOUNT', width: 145),
      ]);
    _tableRows
      ..clear()
      ..addAll(List.generate(
        2,
        (_) => List.generate(_tableColumns.length, (_) => TextEditingController()),
      ));
  }

  void _enableTable() {
    if (_tableEnabled) return;
    setState(() {
      _tableEnabled = true;
      if (_tableColumns.isEmpty || _tableRows.isEmpty) _resetTableDraft();
      _recalculateAllRows();
    });
    _scrollToTable();
  }

  void _scrollToTable() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      final tableContext = _tableSectionKey.currentContext;
      if (tableContext != null) {
        Scrollable.ensureVisible(
          tableContext,
          duration: const Duration(milliseconds: 320),
          curve: Curves.easeOutCubic,
          alignment: 0.08,
        );
        return;
      }
      if (_workspaceScroll.hasClients) {
        _workspaceScroll.animateTo(
          _workspaceScroll.position.maxScrollExtent,
          duration: const Duration(milliseconds: 320),
          curve: Curves.easeOutCubic,
        );
      }
    });
  }

  void _forwardVerticalWheel(PointerSignalEvent event) {
    if (event is! PointerScrollEvent || !_workspaceScroll.hasClients) return;
    if (event.scrollDelta.dy.abs() < event.scrollDelta.dx.abs()) return;
    final position = _workspaceScroll.position;
    final next = (position.pixels + event.scrollDelta.dy)
        .clamp(position.minScrollExtent, position.maxScrollExtent)
        .toDouble();
    if ((next - position.pixels).abs() > 0.5) {
      _workspaceScroll.jumpTo(next);
    }
  }

  void _disableTable() {
    setState(() => _tableEnabled = false);
  }

  void _addTableRow() {
    if (_tableRows.length >= 60) {
      _snack('A request table can contain at most 60 rows.', error: true);
      return;
    }
    setState(() {
      _tableRows.add(List.generate(_tableColumns.length, (_) => TextEditingController()));
    });
    _scrollToTable();
  }

  void _removeTableRow(int index) {
    if (_tableRows.length <= 1) {
      _snack('Keep at least one table row, or remove the table completely.', error: true);
      return;
    }
    final row = _tableRows.removeAt(index);
    for (final cell in row) cell.dispose();
    setState(() {
      _recalculateAllRows();
    });
  }

  void _addTableColumn() {
    if (_tableColumns.length >= 12) {
      _snack('A request table can contain at most 12 columns.', error: true);
      return;
    }
    setState(() {
      _tableColumns.add(
        _RequestTableColumnDraft(
          label: 'COLUMN ${_tableColumns.length + 1}',
          width: 150,
        ),
      );
      for (final row in _tableRows) {
        row.add(TextEditingController());
      }
    });

    // Keep newly added columns immediately reachable without allowing the
    // table to escape/cut the formal document canvas.
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_tableHorizontalScroll.hasClients) return;
      _tableHorizontalScroll.animateTo(
        _tableHorizontalScroll.position.maxScrollExtent,
        duration: const Duration(milliseconds: 220),
        curve: Curves.easeOutCubic,
      );
    });
  }

  void _removeTableColumn(int index) {
    if (_tableColumns.length <= 1) {
      _snack('Keep at least one table column, or remove the table completely.', error: true);
      return;
    }
    final column = _tableColumns.removeAt(index);
    column.label.dispose();
    for (final row in _tableRows) {
      row.removeAt(index).dispose();
    }
    setState(() {
      _recalculateAllRows();
    });
  }

  void _resizeTableColumn(int index, double delta) {
    setState(() {
      _tableColumns[index].width = (_tableColumns[index].width + delta).clamp(80.0, 360.0).toDouble();
    });
  }

  String _normalizedTableLabel(String value) =>
      value.toUpperCase().replaceAll(RegExp(r'[^A-Z0-9]'), '');

  int? _findTableColumnIndex(bool Function(String normalized) matches) {
    for (var i = 0; i < _tableColumns.length; i++) {
      if (matches(_normalizedTableLabel(_tableColumns[i].label.text))) return i;
    }
    return null;
  }

  int? get _quantityColumnIndex => _findTableColumnIndex(
        (label) => label == 'QTY' || label == 'QUANTITY',
      );

  int? get _unitPriceColumnIndex => _findTableColumnIndex(
        (label) => label == 'UNITPRICE' || label == 'PRICE' || label == 'UNITCOST',
      );

  int? get _amountColumnIndex => _findTableColumnIndex(
        (label) => label == 'AMOUNT' || label == 'TOTAL' || label == 'LINEAMOUNT',
      );

  bool _isQuantityColumn(int index) => _quantityColumnIndex == index;
  bool _isUnitPriceColumn(int index) => _unitPriceColumnIndex == index;
  bool _isAmountColumn(int index) => _amountColumnIndex == index;

  bool get _hasAutomaticAmountColumns =>
      _quantityColumnIndex != null &&
      _unitPriceColumnIndex != null &&
      _amountColumnIndex != null;

  double? _parseTableNumber(String raw) {
    final cleaned = raw.replaceAll(RegExp(r'[^0-9.\-]'), '');
    if (cleaned.isEmpty || cleaned == '-' || cleaned == '.') return null;
    return double.tryParse(cleaned);
  }

  String _formatCalculatedNumber(double value) {
    if (value == value.roundToDouble()) return value.toStringAsFixed(0);
    var text = value.toStringAsFixed(2);
    while (text.contains('.') && text.endsWith('0')) {
      text = text.substring(0, text.length - 1);
    }
    if (text.endsWith('.')) text = text.substring(0, text.length - 1);
    return text;
  }

  void _recalculateRow(int rowIndex) {
    final qtyIndex = _quantityColumnIndex;
    final priceIndex = _unitPriceColumnIndex;
    final amountIndex = _amountColumnIndex;
    if (qtyIndex == null || priceIndex == null || amountIndex == null) return;
    if (rowIndex < 0 || rowIndex >= _tableRows.length) return;

    final row = _tableRows[rowIndex];
    if (qtyIndex >= row.length || priceIndex >= row.length || amountIndex >= row.length) return;

    final qty = _parseTableNumber(row[qtyIndex].text);
    final unitPrice = _parseTableNumber(row[priceIndex].text);
    final target = row[amountIndex];

    if (qty == null || unitPrice == null) {
      if (target.text.isNotEmpty) target.clear();
      _syncRequestAmountFromTable();
      return;
    }

    final calculated = _formatCalculatedNumber(qty * unitPrice);
    if (target.text != calculated) {
      target.value = TextEditingValue(
        text: calculated,
        selection: TextSelection.collapsed(offset: calculated.length),
      );
    }
    _syncRequestAmountFromTable();
  }

  void _recalculateAllRows() {
    if (!_hasAutomaticAmountColumns) return;
    for (var i = 0; i < _tableRows.length; i++) {
      _recalculateRow(i);
    }
    _syncRequestAmountFromTable();
  }

  void _syncRequestAmountFromTable() {
    final amountIndex = _amountColumnIndex;
    if (!_tableEnabled || amountIndex == null) return;

    var total = 0.0;
    var found = false;
    for (final row in _tableRows) {
      if (amountIndex >= row.length) continue;
      final value = _parseTableNumber(row[amountIndex].text);
      if (value == null) continue;
      total += value;
      found = true;
    }

    final text = found ? _formatCalculatedNumber(total) : '';
    if (_amount.text != text) {
      _amount.value = TextEditingValue(
        text: text,
        selection: TextSelection.collapsed(offset: text.length),
      );
    }
  }

  Map<String, dynamic> _tablePayload() {
    return <String, dynamic>{
      'enabled': _tableEnabled,
      'department_snapshot': _userDepartment,
      'title': _tableEnabled
          ? (_tableTitle.text.trim().isEmpty ? 'Table description' : _tableTitle.text.trim())
          : '',
      'columns': _tableEnabled
          ? _tableColumns
              .map((column) => <String, dynamic>{
                    'label': column.label.text.trim(),
                    'width': column.width,
                  })
              .toList()
          : <Map<String, dynamic>>[],
      'rows': _tableEnabled
          ? _tableRows
              .map((row) => <String, dynamic>{
                    'cells': row.map((cell) => cell.text.trim()).toList(),
                  })
              .toList()
          : <Map<String, dynamic>>[],
    };
  }

  Map<String, dynamic> get _serverUser {
    final raw = _directory['current_user'];
    if (raw is Map) return raw.map((key, value) => MapEntry(key.toString(), value));
    return const <String, dynamic>{};
  }

  String get _userName {
    final server = (_serverUser['name'] ?? '').toString().trim();
    return server.isEmpty ? widget.userName : server;
  }

  String get _userPosition {
    final server = (_serverUser['position'] ?? '').toString().trim();
    return server.isEmpty ? widget.positionHint : server;
  }

  String _cleanDepartmentValue(dynamic value) {
    final text = value?.toString().trim() ?? '';
    if (text.isEmpty || text.toLowerCase() == 'null') return '';
    return text;
  }

  String _normalizeDepartmentName(String value) {
    var text = value.toLowerCase().trim();
    text = text.replaceAll(RegExp(r'[^a-z0-9]+'), ' ');
    final ignored = <String>{'department', 'dept', 'of', 'the'};
    final words = text
        .split(RegExp(r'\s+'))
        .where((word) => word.isNotEmpty && !ignored.contains(word))
        .toList();
    return words.join(' ');
  }

  String _storedDepartmentFromAccount(Map<String, dynamic> account) {
    for (final value in [
      account['department_name'],
      account['program'],
      widget.departmentHint,
    ]) {
      final cleaned = _cleanDepartmentValue(value);
      if (cleaned.isNotEmpty) return cleaned;
    }
    return '';
  }

  String _resolveDepartmentFromDirectory(
    Map<String, dynamic> account,
    List<Map<String, dynamic>> departments,
  ) {
    // Rockview stores the staff department selection in users.program. The
    // authoritative list of allowed names still comes from departments.php.
    // Resolve exact names first, then normalized legacy names such as
    // "Computer Science" -> "Department of Computer Science".
    final stored = _storedDepartmentFromAccount(account);
    if (stored.isEmpty) return '';

    final storedId = int.tryParse(stored);
    for (final department in departments) {
      final name = _cleanDepartmentValue(department['name']);
      if (name.isEmpty) continue;
      final id = int.tryParse('${department['id'] ?? ''}');
      if (storedId != null && id == storedId) return name;
      if (name.toLowerCase() == stored.toLowerCase()) return name;
    }

    final normalizedStored = _normalizeDepartmentName(stored);
    if (normalizedStored.isNotEmpty) {
      final normalizedMatches = departments.where((department) {
        final name = _cleanDepartmentValue(department['name']);
        return name.isNotEmpty &&
            _normalizeDepartmentName(name) == normalizedStored;
      }).toList();
      if (normalizedMatches.length == 1) {
        return _cleanDepartmentValue(normalizedMatches.first['name']);
      }

      final containsMatches = departments.where((department) {
        final name = _cleanDepartmentValue(department['name']);
        final candidate = _normalizeDepartmentName(name);
        return candidate.isNotEmpty &&
            (candidate.contains(normalizedStored) ||
                normalizedStored.contains(candidate));
      }).toList();
      if (containsMatches.length == 1) {
        return _cleanDepartmentValue(containsMatches.first['name']);
      }
    }

    // Legacy accounts may have been created by the old Staff form when that
    // form silently used placeholder departments. Do not print a red error
    // inside an official letter. Keep the saved staff value for continuity,
    // while the corrected Staff form prevents new invalid values.
    return stored;
  }

  String get _userDepartment => _resolvedDepartment.trim();

  String get _campus {
    final server = (_serverUser['campus'] ?? _directory['selected_campus'] ?? '').toString().trim();
    return server.isEmpty ? widget.campusHint : server;
  }

  Map<String, dynamic>? get _registrarPosition {
    final raw = _directory['positions'];
    if (raw is! List) return null;
    for (final item in raw.whereType<Map>()) {
      final row = item.map((key, value) => MapEntry(key.toString(), value));
      if ((row['stage'] ?? '').toString().toLowerCase() == 'registrar') return row;
    }
    return null;
  }

  bool get _registrarReady {
    final count = int.tryParse('${_registrarPosition?['recipient_count'] ?? 0}') ?? 0;
    return _registrarPosition != null && count > 0;
  }

  String get _registrarTitle {
    final value = (_registrarPosition?['title'] ?? '').toString().trim();
    return value.isEmpty ? 'THE REGISTRAR' : value.toUpperCase();
  }

  Future<void> _loadRoutingContext() async {
    setState(() {
      _loading = true;
      _error = null;
      _departmentIssue = null;
    });

    try {
      final results = await Future.wait<dynamic>([
        RequestWorkflowService.getDirectory(
          campus: widget.campusHint.trim().isEmpty ? null : widget.campusHint,
        ),
        ApiClient.getCurrentLoggedInUser(),
        ApiClient.getDepartments(),
      ]);

      final data = Map<String, dynamic>.from(results[0] as Map);
      final account = Map<String, dynamic>.from(results[1] as Map);
      final departments = <Map<String, dynamic>>[];
      for (final raw in (results[2] as List)) {
        if (raw is Map) {
          departments.add(raw.map((key, value) => MapEntry(key.toString(), value)));
        }
      }

      final department = _resolveDepartmentFromDirectory(account, departments);

      if (!mounted) return;
      setState(() {
        _directory = data;
        _resolvedDepartment = department;
        _departmentIssue = department.isEmpty
            ? 'No department is stored on this staff profile. Select the staff department in Staff Management before dispatching the request.'
            : null;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = RequestWorkflowService.cleanError(e);
        _loading = false;
      });
    }
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    if (_campus.trim().isEmpty) {
      _snack('Your signed-in account has no campus. Assign the campus first.', error: true);
      return;
    }
    if (_userDepartment.isEmpty) {
      _snack(
        _departmentIssue ??
            'Your signed-in staff profile does not resolve to a valid department in the Departments directory.',
        error: true,
      );
      return;
    }
    if (!_registrarReady) {
      _snack('No Registrar administrator is configured for $_campus. Configure Routing Directory first.', error: true);
      return;
    }

    setState(() => _submitting = true);
    try {
      double? amount;
      if (_amount.text.trim().isNotEmpty) {
        amount = double.tryParse(_amount.text.trim().replaceAll(',', ''));
        if (amount == null) {
          _snack('Enter a valid amount or leave the amount field blank.', error: true);
          setState(() => _submitting = false);
          return;
        }
      }

      await RequestWorkflowService.createRequest(
        reference: _subject.text,
        body: _body.text,
        priority: _priority,
        category: _category,
        senderPositionHint: _userPosition,
        amount: amount,
        tableData: _tablePayload(),
      );
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      _snack(RequestWorkflowService.cleanError(e), error: true);
      setState(() => _submitting = false);
    }
  }

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

  String _formalDate() {
    final now = DateTime.now();
    final month = DateFormat('MMMM').format(now).toUpperCase();
    final day = now.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, ${now.year}';
  }

  _CampusLetterheadDetails _campusDetails(String campus) {
    final clean = campus.trim().toUpperCase();
    if (clean.contains('MANSA')) {
      return const _CampusLetterheadDetails(
        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 const _CampusLetterheadDetails(
        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 const _CampusLetterheadDetails(
        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 const _CampusLetterheadDetails(
        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 const _CampusLetterheadDetails(
        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 const _CampusLetterheadDetails(
        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 const _CampusLetterheadDetails(
      campus: 'Head Quarters,Off Mungule Road,Chibombo,Lusaka,',
      box: 'P.O Box 31108, Lusaka.',
      phone: '+260 572 429 305',
      email: 'hq@rockview.ac.zm',
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final compact = size.width < 720;
    final tiny = size.width < 430;

    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 4 : 20, vertical: compact ? 6 : 16),
      backgroundColor: Colors.transparent,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 1020, maxHeight: size.height * 0.97),
        child: Material(
          color: Colors.white,
          borderRadius: BorderRadius.circular(compact ? 12 : 18),
          clipBehavior: Clip.antiAlias,
          elevation: 16,
          child: Column(
            children: [
              _buildDialogHeader(compact),
              Expanded(
                child: _loading
                    ? const Center(child: CircularProgressIndicator(color: _requestGreen))
                    : _error != null
                        ? _DialogError(message: _error!, onRetry: _loadRoutingContext)
                        : _buildLetterWorkspace(compact: compact, tiny: tiny),
              ),
              if (!_loading && _error == null) _buildDialogActions(compact),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDialogHeader(bool compact) {
    return Container(
      padding: EdgeInsets.fromLTRB(compact ? 13 : 20, 11, 8, 11),
      decoration: const BoxDecoration(
        color: _requestGreen,
        border: Border(bottom: BorderSide(color: _requestGold, width: 3)),
      ),
      child: Row(
        children: [
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(color: Colors.white.withOpacity(.12), borderRadius: BorderRadius.circular(10)),
            child: const Icon(Icons.description_outlined, color: Colors.white, size: 20),
          ),
          const SizedBox(width: 10),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('NEW OFFICIAL REQUEST', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 13.5, letterSpacing: .8)),
                SizedBox(height: 2),
                Text('Type directly on the official Rockview request letter', style: TextStyle(color: Color(0xFFDCECE3), fontSize: 10.5)),
              ],
            ),
          ),
          IconButton(
            onPressed: _submitting ? null : () => Navigator.pop(context),
            tooltip: 'Close',
            icon: const Icon(Icons.close_rounded, color: Colors.white),
          ),
        ],
      ),
    );
  }

  Widget _buildLetterWorkspace({required bool compact, required bool tiny}) {
    return ColoredBox(
      color: const Color(0xFFF1F3F2),
      child: Scrollbar(
        controller: _workspaceScroll,
        thumbVisibility: !tiny,
        trackVisibility: false,
        interactive: true,
        child: SingleChildScrollView(
          controller: _workspaceScroll,
          physics: const ClampingScrollPhysics(),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          padding: EdgeInsets.fromLTRB(compact ? 6 : 16, 12, compact ? 10 : 22, 28),
          child: Column(
            children: [
              Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 850), child: _requestTools(compact))),
              const SizedBox(height: 10),
              Center(child: _buildLetterPage(compact: compact, tiny: tiny)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _requestTools(bool compact) {
    final tableButton = _tableEnabled
        ? OutlinedButton.icon(
            onPressed: _disableTable,
            icon: const Icon(Icons.table_rows_outlined, size: 17),
            label: const Text('REMOVE TABLE'),
            style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700),
          )
        : FilledButton.icon(
            onPressed: _enableTable,
            icon: const Icon(Icons.table_chart_outlined, size: 17),
            label: const Text('INSERT TABLE'),
            style: FilledButton.styleFrom(backgroundColor: _requestGreen, foregroundColor: Colors.white),
          );

    return Container(
      padding: const EdgeInsets.all(11),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _requestBorder),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(.035), blurRadius: 12, offset: const Offset(0, 4))],
      ),
      child: compact
          ? Column(
              children: [
                Row(children: [Expanded(child: _categoryField()), const SizedBox(width: 8), Expanded(child: _priorityField())]),
                const SizedBox(height: 8),
                Row(children: [Expanded(child: _amountField()), const SizedBox(width: 8), Expanded(child: tableButton)]),
              ],
            )
          : Row(
              children: [
                Expanded(flex: 2, child: _categoryField()),
                const SizedBox(width: 8),
                Expanded(child: _priorityField()),
                const SizedBox(width: 8),
                Expanded(child: _amountField()),
                const SizedBox(width: 8),
                tableButton,
              ],
            ),
    );
  }

  Widget _categoryField() {
    return DropdownButtonFormField<String>(
      value: _category,
      isExpanded: true,
      decoration: _metaInput('Category', Icons.category_outlined),
      items: _categories.map((v) => DropdownMenuItem(value: v, child: Text(v, overflow: TextOverflow.ellipsis))).toList(),
      onChanged: (v) => setState(() => _category = v ?? 'General'),
    );
  }

  Widget _priorityField() {
    return DropdownButtonFormField<String>(
      value: _priority,
      isExpanded: true,
      decoration: _metaInput('Priority', Icons.flag_outlined),
      items: const [
        DropdownMenuItem(value: 'normal', child: Text('Normal')),
        DropdownMenuItem(value: 'important', child: Text('Important')),
        DropdownMenuItem(value: 'urgent', child: Text('Urgent')),
      ],
      onChanged: (v) => setState(() => _priority = v ?? 'normal'),
    );
  }

  Widget _amountField() {
    final automatic = _tableEnabled && _hasAutomaticAmountColumns;
    return TextFormField(
      controller: _amount,
      readOnly: automatic,
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      decoration: _metaInput(
        automatic ? 'Total amount (auto)' : 'Amount (optional)',
        automatic ? Icons.calculate_outlined : Icons.payments_outlined,
      ).copyWith(
        helperText: automatic ? 'Quantity x unit price, summed automatically' : null,
        helperStyle: const TextStyle(fontSize: 8.5, color: _requestMuted),
      ),
    );
  }

  Widget _buildLetterPage({required bool compact, required bool tiny}) {
    final info = _campusDetails(_campus);
    final serifSize = compact ? 13.5 : 15.0;
    final TextStyle serif = TextStyle(
      fontFamily: 'Times New Roman',
      fontSize: serifSize,
      height: 1.5,
      color: const Color(0xFF202020),
    );
    final serifBold = serif.copyWith(fontWeight: FontWeight.bold);
    final greenStrip = tiny ? 7.0 : (compact ? 10.0 : 28.0);
    final goldStrip = tiny ? 14.0 : (compact ? 20.0 : 54.0);

    return Container(
      width: 850,
      constraints: const BoxConstraints(minHeight: 930),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: const Color(0xFFD6DBD8)),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(.09), blurRadius: 24, offset: const Offset(0, 10))],
      ),
      child: Stack(
        children: [
          Positioned.fill(
            child: IgnorePointer(
              child: Center(
                child: Opacity(
                  opacity: .035,
                  child: Image.asset('assets/logo.png', width: compact ? 270 : 440, fit: BoxFit.contain, errorBuilder: (_, __, ___) => const SizedBox.shrink()),
                ),
              ),
            ),
          ),
          Positioned(left: 0, top: 0, bottom: 0, child: Container(width: greenStrip, color: _requestGreen)),
          Positioned(
            left: greenStrip,
            top: compact ? 44 : 48,
            child: IgnorePointer(
              child: CustomPaint(
                size: Size(goldStrip, compact ? 306 : 579),
                painter: _RequestSideRibbonPainter(
                  goldHeight: compact ? 276 : 530,
                  pointerHeight: compact ? 30 : 49,
                ),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(compact ? 28 : 96, compact ? 22 : 18, compact ? 18 : 54, compact ? 54 : 72),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildLetterhead(info, compact),
                  SizedBox(height: compact ? 22 : 28),
                  _letterMetaRow('TO:', _registrarTitle, serifBold, locked: true),
                  const SizedBox(height: 9),
                  _letterMetaRow('FROM:', '${_userName.toUpperCase()} - ${_userPosition.toUpperCase()}', serifBold, locked: true),
                  const SizedBox(height: 9),
                  _letterMetaRow('DATE:', _formalDate(), serif, locked: true),
                  SizedBox(height: compact ? 18 : 24),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(width: compact ? 44 : 52, child: Text('RE:', style: serifBold)),
                      Expanded(
                        child: TextFormField(
                          controller: _subject,
                          maxLength: 240,
                          textCapitalization: TextCapitalization.characters,
                          style: serifBold,
                          decoration: InputDecoration(
                            counterText: '',
                            isDense: true,
                            hintText: 'TYPE THE SUBJECT OF THE REQUEST',
                            hintStyle: serif.copyWith(color: Colors.grey.shade400, fontWeight: FontWeight.normal),
                            contentPadding: const EdgeInsets.only(bottom: 4),
                            enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Color(0xFF4A4A4A))),
                            focusedBorder: const UnderlineInputBorder(borderSide: BorderSide(color: _requestGold, width: 1.7)),
                          ),
                          validator: (v) => (v ?? '').trim().isEmpty ? 'Enter the RE/subject.' : null,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: compact ? 18 : 24),
                  TextFormField(
                    controller: _body,
                    minLines: compact ? 7 : 8,
                    maxLines: null,
                    textCapitalization: TextCapitalization.sentences,
                    style: serif,
                    decoration: InputDecoration(
                      hintText: 'Type the official request here. For example: I write to request approval for...',
                      hintStyle: serif.copyWith(color: Colors.grey.shade500),
                      filled: true,
                      fillColor: Colors.white.withOpacity(.78),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      enabledBorder: InputBorder.none,
                      focusedBorder: InputBorder.none,
                    ),
                    validator: (v) => (v ?? '').trim().isEmpty ? 'Type the body of the request.' : null,
                  ),
                  if (_tableEnabled) ...[
                    const SizedBox(height: 14),
                    KeyedSubtree(
                      key: _tableSectionKey,
                      child: _buildEditableRequestTable(compact: compact, serif: serif, serifBold: serifBold),
                    ),
                  ],
                  const SizedBox(height: 24),
                  Text('Yours Faithfully,', style: serif),
                  const SizedBox(height: 8),
                  Transform(
                    transform: Matrix4.skewX(-0.15),
                    child: Text(
                      _userName,
                      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(_userName, style: serif),
                  const SizedBox(height: 3),
                  Text(
                    _userPosition,
                    style: serifBold.copyWith(decoration: TextDecoration.underline),
                  ),
                  const SizedBox(height: 3),
                  if (_userDepartment.isNotEmpty)
                    Text(
                      'Department: $_userDepartment',
                      style: serif.copyWith(
                        fontWeight: FontWeight.w600,
                        color: _requestMuted,
                      ),
                    ),
                  const SizedBox(height: 34),
                  _lockedCampusBanner(compact),
                ],
              ),
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              height: compact ? 32 : 47,
              color: _requestGreen,
              alignment: Alignment.center,
              child: Text(
                '“ PROFICIENCY AND EXCELLENCE ”',
                style: TextStyle(color: Colors.white, fontSize: compact ? 9 : 12, fontWeight: FontWeight.bold, letterSpacing: compact ? 1.5 : 2.6),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEditableRequestTable({
    required bool compact,
    required TextStyle serif,
    required TextStyle serifBold,
  }) {
    final totalWidth = _tableColumns.fold<double>(
      0,
      (sum, column) => sum + column.width,
    );
    const actionWidth = 44.0;
    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 + actionWidth;
        final rawContentWidth = totalWidth + actionWidth;
        final contentWidth = rawContentWidth < viewportWidth
            ? viewportWidth
            : rawContentWidth;
        final needsScroll = rawContentWidth > viewportWidth + 1;

        return RepaintBoundary(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'TABLE',
                          style: TextStyle(
                            color: _requestGreen,
                            fontSize: compact ? 9.0 : 9.8,
                            fontWeight: FontWeight.w900,
                            letterSpacing: .9,
                          ),
                        ),
                        TextFormField(
                          controller: _tableTitle,
                          style: serifBold.copyWith(
                            fontSize: compact ? 12.0 : 13.0,
                          ),
                          decoration: InputDecoration(
                            isDense: true,
                            hintText: 'Table description',
                            hintStyle: serif.copyWith(
                              color: Colors.grey.shade500,
                              fontSize: compact ? 11.5 : 12.5,
                            ),
                            border: InputBorder.none,
                            contentPadding: const EdgeInsets.only(
                              top: 2,
                              bottom: 5,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(width: 8),
                  Wrap(
                    spacing: 5,
                    runSpacing: 5,
                    alignment: WrapAlignment.end,
                    children: [
                      _smallTableButton(
                        Icons.view_column_outlined,
                        'ADD COLUMN',
                        _addTableColumn,
                      ),
                      _smallTableButton(
                        Icons.table_rows_outlined,
                        'ADD ROW',
                        _addTableRow,
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 7),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(
                  horizontal: 10,
                  vertical: 8,
                ),
                decoration: BoxDecoration(
                  color: const Color(0xFFF7FAF8),
                  borderRadius: BorderRadius.circular(9),
                  border: Border.all(color: _requestBorder),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Padding(
                      padding: EdgeInsets.only(top: 1),
                      child: Icon(
                        Icons.info_outline_rounded,
                        size: 15,
                        color: _requestGreen,
                      ),
                    ),
                    const SizedBox(width: 7),
                    Expanded(
                      child: Text(
                        needsScroll
                            ? 'The table stays inside the request document. Use the horizontal bar below for additional columns; continue scrolling the request vertically as normal.'
                            : 'Type directly in the cells. Column widths, headings and every cell value are saved with the request.',
                        style: const TextStyle(
                          fontSize: 9.1,
                          color: _requestMuted,
                          height: 1.35,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 8),
              Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: grid),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(.025),
                      blurRadius: 10,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                clipBehavior: Clip.antiAlias,
                child: Listener(
                  onPointerSignal: _forwardVerticalWheel,
                  child: Scrollbar(
                    controller: _tableHorizontalScroll,
                    thumbVisibility: needsScroll,
                    trackVisibility: needsScroll,
                    interactive: true,
                    scrollbarOrientation: ScrollbarOrientation.bottom,
                    child: SingleChildScrollView(
                      controller: _tableHorizontalScroll,
                      scrollDirection: Axis.horizontal,
                      physics: const ClampingScrollPhysics(),
                      padding: EdgeInsets.only(
                        bottom: needsScroll ? 11 : 0,
                      ),
                      child: SizedBox(
                        width: contentWidth,
                        child: Column(
                          children: [
                            SizedBox(
                              height: 48,
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  ...List.generate(
                                    _tableColumns.length,
                                    (index) {
                                      final column = _tableColumns[index];
                                      return Container(
                                        width: column.width,
                                        padding: const EdgeInsets.fromLTRB(
                                          9,
                                          3,
                                          2,
                                          3,
                                        ),
                                        decoration: const BoxDecoration(
                                          color: headerFill,
                                          border: Border(
                                            right: BorderSide(color: grid),
                                            bottom: BorderSide(color: grid),
                                          ),
                                        ),
                                        child: Row(
                                          children: [
                                            Expanded(
                                              child: TextField(
                                                controller: column.label,
                                                textAlignVertical:
                                                    TextAlignVertical.center,
                                                style: serifBold.copyWith(
                                                  fontFamily: 'Arial',
                                                  fontSize:
                                                      compact ? 10.5 : 11.4,
                                                  color: _requestInk,
                                                  letterSpacing: .15,
                                                ),
                                                textCapitalization:
                                                    TextCapitalization.characters,
                                                onChanged: (_) {
                                                  setState(() {
                                                    _recalculateAllRows();
                                                  });
                                                },
                                                decoration:
                                                    const InputDecoration(
                                                  border: InputBorder.none,
                                                  isDense: true,
                                                  contentPadding:
                                                      EdgeInsets.symmetric(
                                                    vertical: 10,
                                                  ),
                                                ),
                                              ),
                                            ),
                                            PopupMenuButton<String>(
                                              tooltip: 'Column options',
                                              padding: EdgeInsets.zero,
                                              icon: const Icon(
                                                Icons.more_vert_rounded,
                                                size: 16,
                                                color: _requestMuted,
                                              ),
                                              onSelected: (value) {
                                                if (value == 'wider') {
                                                  _resizeTableColumn(index, 30);
                                                }
                                                if (value == 'narrower') {
                                                  _resizeTableColumn(index, -30);
                                                }
                                                if (value == 'delete') {
                                                  _removeTableColumn(index);
                                                }
                                              },
                                              itemBuilder: (_) => const [
                                                PopupMenuItem(
                                                  value: 'wider',
                                                  child: Text(
                                                    'Make column wider',
                                                  ),
                                                ),
                                                PopupMenuItem(
                                                  value: 'narrower',
                                                  child: Text(
                                                    'Make column narrower',
                                                  ),
                                                ),
                                                PopupMenuDivider(),
                                                PopupMenuItem(
                                                  value: 'delete',
                                                  child: Text('Remove column'),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      );
                                    },
                                  ),
                                  Container(
                                    width: actionWidth,
                                    alignment: Alignment.center,
                                    decoration: const BoxDecoration(
                                      color: headerFill,
                                      border: Border(
                                        bottom: BorderSide(color: grid),
                                      ),
                                    ),
                                    child: const Icon(
                                      Icons.tune_rounded,
                                      size: 15,
                                      color: _requestMuted,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            ...List.generate(
                              _tableRows.length,
                              (rowIndex) {
                                final row = _tableRows[rowIndex];
                                final rowColor = rowIndex.isOdd
                                    ? alternateRow
                                    : Colors.white;
                                return SizedBox(
                                  height: 52,
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.stretch,
                                    children: [
                                      ...List.generate(
                                        _tableColumns.length,
                                        (columnIndex) {
                                          final column =
                                              _tableColumns[columnIndex];
                                          final isQuantity =
                                              _isQuantityColumn(columnIndex);
                                          final isUnitPrice =
                                              _isUnitPriceColumn(columnIndex);
                                          final isAmount =
                                              _isAmountColumn(columnIndex) &&
                                                  _quantityColumnIndex != null &&
                                                  _unitPriceColumnIndex != null;
                                          final numeric =
                                              isQuantity || isUnitPrice || isAmount;
                                          return Container(
                                            width: column.width,
                                            padding: const EdgeInsets.symmetric(
                                              horizontal: 9,
                                              vertical: 3,
                                            ),
                                            decoration: BoxDecoration(
                                              color: isAmount
                                                  ? const Color(0xFFF3F8F5)
                                                  : rowColor,
                                              border: const Border(
                                                right:
                                                    BorderSide(color: grid),
                                                bottom:
                                                    BorderSide(color: grid),
                                              ),
                                            ),
                                            child: TextField(
                                              controller: row[columnIndex],
                                              readOnly: isAmount,
                                              keyboardType: numeric
                                                  ? const TextInputType.numberWithOptions(
                                                      decimal: true,
                                                    )
                                                  : TextInputType.text,
                                              minLines: 1,
                                              maxLines: 2,
                                              textAlignVertical:
                                                  TextAlignVertical.center,
                                              style: serif.copyWith(
                                                fontFamily: 'Arial',
                                                fontSize:
                                                    compact ? 10.7 : 11.6,
                                                height: 1.25,
                                                color: _requestInk,
                                              ),
                                              onChanged: isAmount
                                                  ? null
                                                  : (_) {
                                                      if (isQuantity ||
                                                          isUnitPrice) {
                                                        _recalculateRow(rowIndex);
                                                        setState(() {});
                                                      }
                                                    },
                                              decoration: InputDecoration(
                                                border: InputBorder.none,
                                                isDense: true,
                                                hintText: isAmount
                                                    ? 'Auto'
                                                    : (rowIndex == 0
                                                        ? 'Enter value'
                                                        : null),
                                                hintStyle: TextStyle(
                                                  color:
                                                      Colors.grey.shade400,
                                                  fontSize:
                                                      compact ? 10.0 : 10.8,
                                                ),
                                                contentPadding:
                                                    const EdgeInsets.symmetric(
                                                  vertical: 9,
                                                ),
                                              ),
                                            ),
                                          );
                                        },
                                      ),
                                      Container(
                                        width: actionWidth,
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          color: rowColor,
                                          border: const Border(
                                            bottom: BorderSide(color: grid),
                                          ),
                                        ),
                                        child: IconButton(
                                          onPressed: () =>
                                              _removeTableRow(rowIndex),
                                          tooltip: 'Remove row',
                                          padding: EdgeInsets.zero,
                                          visualDensity: VisualDensity.compact,
                                          icon: Icon(
                                            Icons.remove_circle_outline_rounded,
                                            color: Colors.red.shade500,
                                            size: 17,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _smallTableButton(IconData icon, String label, VoidCallback onTap) {
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(8),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: _requestBorder),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, size: 14, color: _requestGreen),
              const SizedBox(width: 5),
              Text(label, style: const TextStyle(fontSize: 8.5, color: _requestInk, fontWeight: FontWeight.w900, letterSpacing: .25)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLetterhead(_CampusLetterheadDetails info, bool compact) {
    return Center(
      child: Column(
        children: [
          Image.asset(
            'assets/logo.png',
            height: compact ? 60 : 86,
            errorBuilder: (_, __, ___) => Icon(Icons.school_rounded, color: _requestGreen, size: compact ? 58 : 76),
          ),
          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 ? 25 : 41,
                fontWeight: FontWeight.w900,
                letterSpacing: .5,
              ),
            ),
          ),
          const SizedBox(height: 1),
          Text(
            '${info.campus} ${info.box}',
            textAlign: TextAlign.center,
            style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 10.2 : 12.2, fontWeight: FontWeight.bold, height: 1.18),
          ),
          Text(
            'Office line:  ${info.phone}',
            textAlign: TextAlign.center,
            style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 10.0 : 11.7, 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 ? 9.5 : 11.0, fontWeight: FontWeight.bold)),
              Text('www.rockviewuniversity.ac', style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 9.5 : 11.0, color: Colors.blue.shade700, decoration: TextDecoration.underline)),
              Text('Email:', style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 9.5 : 11.0, fontWeight: FontWeight.bold)),
              Text(info.email, style: TextStyle(fontFamily: 'Times New Roman', fontSize: compact ? 9.5 : 11.0, 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 ? 9.2 : 10.7),
          ),
          const SizedBox(height: 10),
          Container(height: 2, color: const Color(0xFF00A05A)),
        ],
      ),
    );
  }

  Widget _lockedCampusBanner(bool compact) {
    final ready = _registrarReady;
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(compact ? 9 : 11),
      decoration: BoxDecoration(
        color: ready ? _requestGreen.withOpacity(.045) : Colors.red.withOpacity(.045),
        border: Border.all(color: ready ? _requestGreen.withOpacity(.17) : Colors.red.withOpacity(.20)),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(ready ? Icons.lock_person_outlined : Icons.warning_amber_rounded, color: ready ? _requestGreen : Colors.red.shade700, size: 17),
          const SizedBox(width: 7),
          Expanded(
            child: Text(
              ready
                  ? 'Protected routing: this form belongs to $_campus and will be delivered first to the Registrar assigned to that campus. Staff cannot change the destination.'
                  : '$_userPosition routing is not ready for $_campus. An administrator must assign the Registrar account in Routing Directory before this request can be dispatched.',
              style: TextStyle(color: ready ? _requestMuted : Colors.red.shade800, fontSize: compact ? 9.5 : 10.4, height: 1.35, fontWeight: FontWeight.w600),
            ),
          ),
        ],
      ),
    );
  }

  Widget _letterMetaRow(String label, String value, TextStyle style, {bool locked = false}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(width: 56, child: Text(label, style: style.copyWith(fontWeight: FontWeight.bold))),
        Expanded(
          child: Row(
            children: [
              Expanded(child: Text(value, style: style)),
              if (locked) const Padding(padding: EdgeInsets.only(left: 5), child: Icon(Icons.lock_outline_rounded, size: 12, color: _requestMuted)),
            ],
          ),
        ),
      ],
    );
  }

  InputDecoration _metaInput(String label, IconData icon) {
    return InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, size: 16, color: _requestGreen),
      filled: true,
      fillColor: const Color(0xFFF8FAF9),
      isDense: true,
      contentPadding: const EdgeInsets.symmetric(horizontal: 9, vertical: 10),
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: _requestBorder)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: _requestBorder)),
      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: _requestGold, width: 1.4)),
    );
  }

  Widget _buildDialogActions(bool compact) {
    final dispatch = FilledButton.icon(
      onPressed: _submitting || !_registrarReady || _userDepartment.isEmpty
          ? null
          : _submit,
      style: FilledButton.styleFrom(
        backgroundColor: _requestGreen,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 15),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
      ),
      icon: _submitting
          ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
          : const Icon(Icons.send_rounded, size: 18),
      label: Text(_submitting ? 'DISPATCHING...' : 'DISPATCH TO CAMPUS REGISTRAR', style: const TextStyle(fontSize: 10.5, fontWeight: FontWeight.w900, letterSpacing: .45)),
    );

    return Container(
      padding: EdgeInsets.symmetric(horizontal: compact ? 10 : 18, vertical: 10),
      decoration: const BoxDecoration(color: Color(0xFFF8FAF9), border: Border(top: BorderSide(color: _requestBorder))),
      child: compact
          ? Row(
              children: [
                Expanded(child: OutlinedButton(onPressed: _submitting ? null : () => Navigator.pop(context), child: const Text('DISCARD'))),
                const SizedBox(width: 7),
                Expanded(flex: 2, child: dispatch),
              ],
            )
          : Row(
              children: [
                const Expanded(child: Text('The PHP backend verifies the logged-in campus and the Registrar administrator before the letter is saved.', style: TextStyle(color: _requestMuted, fontSize: 10.3))),
                TextButton(onPressed: _submitting ? null : () => Navigator.pop(context), child: const Text('DISCARD')),
                const SizedBox(width: 8),
                dispatch,
              ],
            ),
    );
  }
}

class _RequestTableColumnDraft {
  final TextEditingController label;
  double width;

  _RequestTableColumnDraft({required String label, required this.width}) : label = TextEditingController(text: label);
}

class _RequestSideRibbonPainter extends CustomPainter {
  final double goldHeight;
  final double pointerHeight;

  const _RequestSideRibbonPainter({
    required this.goldHeight,
    required this.pointerHeight,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final width = size.width;
    final joinRise = pointerHeight * 0.38;
    final joinLeftY = goldHeight - joinRise;
    final joinRightY = goldHeight;

    final goldPaint = Paint()
      ..color = const Color(0xFFF2A500)
      ..style = PaintingStyle.fill
      ..isAntiAlias = true;
    final blackPaint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.fill
      ..isAntiAlias = true;

    final gold = Path()
      ..moveTo(0, 0)
      ..lineTo(width, goldHeight * 0.055)
      ..lineTo(width, joinRightY)
      ..lineTo(0, joinLeftY)
      ..close();
    canvas.drawPath(gold, goldPaint);

    // The black pointer is painted directly on top of the exact gold join.
    // Because both shapes share this edge inside the same painter, there is
    // no white seam/gap between the amber ribbon and the black pointer.
    final pointer = Path()
      ..moveTo(0, joinLeftY - 0.75)
      ..lineTo(width, joinRightY - 0.75)
      ..lineTo(0, joinLeftY + pointerHeight)
      ..close();
    canvas.drawPath(pointer, blackPaint);
  }

  @override
  bool shouldRepaint(covariant _RequestSideRibbonPainter oldDelegate) {
    return oldDelegate.goldHeight != goldHeight ||
        oldDelegate.pointerHeight != pointerHeight;
  }
}


class _CampusLetterheadDetails {
  final String campus;
  final String box;
  final String phone;
  final String email;

  const _CampusLetterheadDetails({
    required this.campus,
    required this.box,
    required this.phone,
    required this.email,
  });
}

class _DialogError extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _DialogError({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: 46, color: Colors.red.shade300),
            const SizedBox(height: 12),
            Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _requestMuted)),
            const SizedBox(height: 14),
            OutlinedButton.icon(onPressed: onRetry, icon: const Icon(Icons.refresh_rounded), label: const Text('Retry')),
          ],
        ),
      ),
    );
  }
}

class _RequestNotificationsDialog extends StatefulWidget {
  final ValueChanged<int> onOpenRequest;
  const _RequestNotificationsDialog({required this.onOpenRequest});

  @override
  State<_RequestNotificationsDialog> createState() => _RequestNotificationsDialogState();
}

class _RequestNotificationsDialogState extends State<_RequestNotificationsDialog> {
  bool _loading = true;
  String? _error;
  List<Map<String, dynamic>> _items = [];

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final rows = await RequestWorkflowService.getNotifications();
      if (!mounted) return;
      setState(() {
        _items = rows;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = RequestWorkflowService.cleanError(e);
        _loading = false;
      });
    }
  }

  Future<void> _markAll() async {
    await RequestWorkflowService.markAllNotificationsRead();
    if (!mounted) return;
    setState(() {
      for (final item in _items) item['is_read'] = true;
    });
  }

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

  IconData _icon(String type) {
    switch (type) {
      case 'approved': return Icons.verified_rounded;
      case 'declined': return Icons.cancel_rounded;
      case 'routed': return Icons.alt_route_rounded;
      default: return Icons.assignment_late_rounded;
    }
  }

  Color _color(String type) {
    switch (type) {
      case 'approved': return _requestGreen;
      case 'declined': return Colors.red.shade700;
      case 'routed': return _requestGold;
      default: return const Color(0xFF245A88);
    }
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.sizeOf(context).width < 620;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 8 : 24, vertical: 24),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
      clipBehavior: Clip.antiAlias,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 640, maxHeight: MediaQuery.sizeOf(context).height * 0.82),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.fromLTRB(18, 15, 10, 15),
              color: _requestGreen,
              child: Row(
                children: [
                  const Icon(Icons.notifications_active_rounded, color: Colors.white),
                  const SizedBox(width: 10),
                  const Expanded(child: Text('REQUEST NOTIFICATIONS', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, letterSpacing: 0.6))),
                  TextButton(onPressed: _items.isEmpty ? null : _markAll, child: const Text('MARK ALL READ', style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w800))),
                  IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded, color: Colors.white)),
                ],
              ),
            ),
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator(color: _requestGreen))
                  : _error != null
                      ? _DialogError(message: _error!, onRetry: _load)
                      : _items.isEmpty
                          ? const Center(child: Text('No workflow notifications yet.', style: TextStyle(color: _requestMuted)))
                          : ListView.separated(
                              padding: const EdgeInsets.all(12),
                              itemCount: _items.length,
                              separatorBuilder: (_, __) => const SizedBox(height: 7),
                              itemBuilder: (context, index) {
                                final item = _items[index];
                                final read = item['is_read'] == true || item['is_read'] == 1 || item['is_read'] == '1';
                                final type = '${item['notification_type'] ?? ''}';
                                return Material(
                                  color: read ? Colors.white : _requestGreen.withOpacity(0.045),
                                  borderRadius: BorderRadius.circular(12),
                                  child: InkWell(
                                    borderRadius: BorderRadius.circular(12),
                                    onTap: () async {
                                      final id = int.tryParse('${item['id'] ?? 0}') ?? 0;
                                      if (!read && id > 0) {
                                        await RequestWorkflowService.markNotificationRead(id);
                                        item['is_read'] = true;
                                      }
                                      if (!mounted) return;
                                      final requestId = int.tryParse('${item['request_id'] ?? 0}') ?? 0;
                                      Navigator.pop(context);
                                      if (requestId > 0) widget.onOpenRequest(requestId);
                                    },
                                    child: Padding(
                                      padding: const EdgeInsets.all(13),
                                      child: Row(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            width: 40,
                                            height: 40,
                                            decoration: BoxDecoration(color: _color(type).withOpacity(0.10), borderRadius: BorderRadius.circular(11)),
                                            child: Icon(_icon(type), color: _color(type), size: 20),
                                          ),
                                          const SizedBox(width: 12),
                                          Expanded(
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Row(
                                                  children: [
                                                    Expanded(child: Text('${item['title'] ?? 'Request update'}', style: const TextStyle(fontWeight: FontWeight.w900, color: _requestInk, fontSize: 13))),
                                                    if (!read) Container(width: 7, height: 7, decoration: const BoxDecoration(color: _requestGold, shape: BoxShape.circle)),
                                                  ],
                                                ),
                                                const SizedBox(height: 4),
                                                Text('${item['body'] ?? ''}', style: const TextStyle(color: _requestMuted, fontSize: 11.5, height: 1.35)),
                                                const SizedBox(height: 6),
                                                Text(_time(item['created_at']), style: const TextStyle(color: _requestMuted, fontSize: 10, fontWeight: FontWeight.w600)),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
            ),
          ],
        ),
      ),
    );
  }
}
