// lib/features/admin/tabs/staff_lectures/past_lectures_sub_tab.dart

import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';

import '../../../../core/networks/api_client.dart';

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);
const Color _ink = Color(0xFF24332B);
const Color _softBackground = Color(0xFFF4F6F5);

/// Kept under the existing class/file name so the parent navigation does not
/// need a breaking rename. This tab is now the Lecturer Reporting workspace.
class PastLecturesSubTab extends StatefulWidget {
  const PastLecturesSubTab({super.key});

  @override
  State<PastLecturesSubTab> createState() => _PastLecturesSubTabState();
}

class _PastLecturesSubTabState extends State<PastLecturesSubTab> {
  final TextEditingController _searchController = TextEditingController();
  List<Map<String, dynamic>> _staff = [];
  bool _loading = true;
  String? _error;
  String _campusFilter = 'All Campuses';

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

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

  Future<void> _loadStaff() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final rows = await ApiClient.getStaff();
      final clean = <Map<String, dynamic>>[];
      for (final row in rows) {
        clean.add(row.map((key, value) => MapEntry(key.toString(), value)));
      }
      clean.sort((a, b) => _staffName(a).toLowerCase().compareTo(_staffName(b).toLowerCase()));
      if (mounted) setState(() => _staff = clean);
    } catch (e) {
      if (mounted) setState(() => _error = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  String _text(dynamic value, [String fallback = '']) {
    final text = value?.toString().trim() ?? '';
    return text.isEmpty || text.toLowerCase() == 'null' ? fallback : text;
  }

  String _staffName(Map<String, dynamic> staff) =>
      _text(staff['full_name'], _text(staff['name'], 'Unnamed Staff'));

  String _staffCampus(Map<String, dynamic> staff) =>
      _text(staff['campus'], 'Campus not assigned');

  String _staffSchool(Map<String, dynamic> staff) =>
      _text(staff['school'], 'School not assigned');

  String _staffDepartment(Map<String, dynamic> staff) => _text(
        staff['department'],
        _text(staff['program'], 'Department not assigned'),
      );

  List<String> get _campuses {
    final values = _staff
        .map(_staffCampus)
        .where((value) => value != 'Campus not assigned')
        .toSet()
        .toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return ['All Campuses', ...values];
  }

  List<Map<String, dynamic>> get _visibleStaff {
    final query = _searchController.text.trim().toLowerCase();
    return _staff.where((staff) {
      if (_campusFilter != 'All Campuses' && _staffCampus(staff) != _campusFilter) {
        return false;
      }
      if (query.isEmpty) return true;
      final haystack = [
        _staffName(staff),
        _staffCampus(staff),
        _staffSchool(staff),
        _staffDepartment(staff),
        _text(staff['email']),
      ].join(' ').toLowerCase();
      return haystack.contains(query);
    }).toList();
  }

  Uint8List? _legacyBase64Bytes(String raw) {
    try {
      final source = raw.startsWith('data:image') && raw.contains(',')
          ? raw.substring(raw.indexOf(',') + 1)
          : raw;
      return base64Decode(source);
    } catch (_) {
      return null;
    }
  }

  Widget _profileImage(dynamic rawValue) {
    final raw = _text(rawValue);
    if (raw.isEmpty) return _profileFallback();

    if (raw.startsWith('http://') ||
        raw.startsWith('https://') ||
        raw.startsWith('uploads/') ||
        raw.startsWith('/uploads/')) {
      final url = ApiClient.resolveMediaUrl(raw);
      return Image.network(
        url,
        fit: BoxFit.cover,
        errorBuilder: (_, __, ___) => _profileFallback(),
      );
    }

    final bytes = _legacyBase64Bytes(raw);
    if (bytes != null) {
      return Image.memory(
        bytes,
        fit: BoxFit.cover,
        errorBuilder: (_, __, ___) => _profileFallback(),
      );
    }

    return _profileFallback();
  }

  Widget _profileFallback() => Container(
        color: const Color(0xFFEFF3F0),
        alignment: Alignment.center,
        child: const Icon(Icons.person_rounded, size: 40, color: Color(0xFF8D9B92)),
      );

  Future<void> _openReportForm(Map<String, dynamic> staff) async {
    final submitted = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _LecturerReportDialog(
        lecturer: staff,
        profile: _profileImage(staff['profile_picture']),
        lecturerName: _staffName(staff),
        campus: _staffCampus(staff),
        school: _staffSchool(staff),
        department: _staffDepartment(staff),
      ),
    );

    if (!mounted || submitted != true) return;
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'Lecturer report submitted successfully.',
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
        ),
        backgroundColor: _darkGreen,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: _softBackground,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final width = constraints.maxWidth;
          final horizontalPadding = width < 700 ? 14.0 : 28.0;
          return Padding(
            padding: EdgeInsets.fromLTRB(horizontalPadding, 0, horizontalPadding, 24),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildHero(width),
                const SizedBox(height: 18),
                _buildToolbar(width),
                const SizedBox(height: 18),
                Expanded(child: _buildContent(width)),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildHero(double width) {
    final compact = width < 760;
    final titleBlock = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'REPORT LECTURER',
          style: TextStyle(
            color: _darkGreen,
            fontSize: 24,
            fontWeight: FontWeight.w900,
            letterSpacing: 1.2,
          ),
        ),
        const SizedBox(height: 6),
        Text(
          'Select a staff member to open the reporting form. Reports are saved securely against the selected lecturer record.',
          style: TextStyle(color: Colors.grey.shade600, fontSize: 14.5, height: 1.45),
        ),
      ],
    );

    final notice = Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF8ED),
        border: Border.all(color: const Color(0xFFF2D7AC)),
      ),
      child: const Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.privacy_tip_outlined, color: _standardGold, size: 20),
          SizedBox(width: 9),
          Flexible(
            child: Text(
              'Reports should be factual, specific and submitted in good faith.',
              style: TextStyle(color: _ink, fontWeight: FontWeight.w700, fontSize: 12),
            ),
          ),
        ],
      ),
    );

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: const Color(0xFFDCE3DE)),
        boxShadow: const [
          BoxShadow(color: Color(0x11000000), blurRadius: 16, offset: Offset(0, 6)),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(height: 4, color: _standardGold),
          Padding(
            padding: EdgeInsets.all(compact ? 20 : 28),
            child: compact
                ? Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [titleBlock, const SizedBox(height: 16), notice],
                  )
                : Row(
                    children: [
                      Expanded(child: titleBlock),
                      const SizedBox(width: 24),
                      Flexible(child: notice),
                    ],
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildToolbar(double width) {
    final search = TextField(
      controller: _searchController,
      onChanged: (_) => setState(() {}),
      decoration: InputDecoration(
        hintText: 'Search lecturer, campus, school or department...',
        prefixIcon: const Icon(Icons.search_rounded, color: _darkGreen),
        suffixIcon: _searchController.text.isNotEmpty
            ? IconButton(
                onPressed: () {
                  _searchController.clear();
                  setState(() {});
                },
                icon: const Icon(Icons.close_rounded),
              )
            : null,
        filled: true,
        fillColor: Colors.white,
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: Color(0xFFD7DFDA)),
        ),
        focusedBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: _darkGreen, width: 2),
        ),
      ),
    );

    final campus = DropdownButtonFormField<String>(
      value: _campuses.contains(_campusFilter) ? _campusFilter : 'All Campuses',
      isExpanded: true,
      decoration: const InputDecoration(
        labelText: 'Campus',
        prefixIcon: Icon(Icons.domain_outlined, color: _standardGold),
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: Color(0xFFD7DFDA)),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: _darkGreen, width: 2),
        ),
      ),
      items: _campuses.map((value) => DropdownMenuItem(value: value, child: Text(value))).toList(),
      onChanged: (value) => setState(() => _campusFilter = value ?? 'All Campuses'),
    );

    final refresh = OutlinedButton.icon(
      onPressed: _loading ? null : _loadStaff,
      icon: const Icon(Icons.refresh_rounded),
      label: const Text('REFRESH'),
      style: OutlinedButton.styleFrom(
        foregroundColor: _darkGreen,
        side: const BorderSide(color: _darkGreen),
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      ),
    );

    if (width < 840) {
      return Column(
        children: [
          search,
          const SizedBox(height: 10),
          Row(children: [Expanded(child: campus), const SizedBox(width: 10), refresh]),
        ],
      );
    }

    return Row(
      children: [
        Expanded(flex: 5, child: search),
        const SizedBox(width: 12),
        Expanded(flex: 2, child: campus),
        const SizedBox(width: 12),
        refresh,
      ],
    );
  }

  Widget _buildContent(double width) {
    if (_loading) {
      return const Center(child: CircularProgressIndicator(color: _darkGreen));
    }

    if (_error != null) {
      return _messagePanel(
        Icons.cloud_off_outlined,
        'Unable to load staff',
        _error!,
        action: _loadStaff,
      );
    }

    final staff = _visibleStaff;
    if (_staff.isEmpty) {
      return _messagePanel(
        Icons.people_outline,
        'No staff records available',
        'Staff members must exist in the users database before a lecturer can be selected for reporting.',
      );
    }

    if (staff.isEmpty) {
      return _messagePanel(
        Icons.search_off_rounded,
        'No matching lecturer',
        'Try another name, campus, school or department.',
      );
    }

    final columns = width >= 1420
        ? 4
        : width >= 1050
            ? 3
            : width >= 680
                ? 2
                : 1;

    return GridView.builder(
      padding: const EdgeInsets.only(bottom: 20),
      itemCount: staff.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: columns,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        mainAxisExtent: 324,
      ),
      itemBuilder: (context, index) {
        final person = staff[index];
        return _ReportStaffCard(
          name: _staffName(person),
          campus: _staffCampus(person),
          school: _staffSchool(person),
          department: _staffDepartment(person),
          profile: _profileImage(person['profile_picture']),
          onTap: () => _openReportForm(person),
        );
      },
    );
  }

  Widget _messagePanel(IconData icon, String title, String message, {VoidCallback? action}) {
    return Center(
      child: Container(
        constraints: const BoxConstraints(maxWidth: 540),
        padding: const EdgeInsets.all(34),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: const Color(0xFFDCE3DE)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 78,
              height: 78,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: const Color(0xFFF5F8F6),
                border: Border.all(color: const Color(0xFFE1E8E3)),
              ),
              child: Icon(icon, size: 38, color: _darkGreen),
            ),
            const SizedBox(height: 18),
            Text(title, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 20)),
            const SizedBox(height: 8),
            Text(message, textAlign: TextAlign.center, style: const TextStyle(color: Color(0xFF6F7F75), height: 1.45)),
            if (action != null) ...[
              const SizedBox(height: 20),
              OutlinedButton.icon(
                onPressed: action,
                icon: const Icon(Icons.refresh_rounded),
                label: const Text('TRY AGAIN'),
                style: OutlinedButton.styleFrom(
                  foregroundColor: _darkGreen,
                  side: const BorderSide(color: _darkGreen),
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

class _ReportStaffCard extends StatefulWidget {
  final String name;
  final String campus;
  final String school;
  final String department;
  final Widget profile;
  final VoidCallback onTap;

  const _ReportStaffCard({
    required this.name,
    required this.campus,
    required this.school,
    required this.department,
    required this.profile,
    required this.onTap,
  });

  @override
  State<_ReportStaffCard> createState() => _ReportStaffCardState();
}

class _ReportStaffCardState extends State<_ReportStaffCard> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 180),
          transform: Matrix4.translationValues(0, _hovered ? -3 : 0, 0),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(
              color: _hovered ? _standardGold : const Color(0xFFDCE3DE),
              width: _hovered ? 1.5 : 1,
            ),
            boxShadow: [
              BoxShadow(
                color: _hovered ? const Color(0x19000000) : const Color(0x0D000000),
                blurRadius: _hovered ? 20 : 10,
                offset: const Offset(0, 7),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(height: 4, color: _hovered ? _standardGold : _darkGreen),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(18),
                  child: Column(
                    children: [
                      Container(
                        width: 82,
                        height: 82,
                        padding: const EdgeInsets.all(3),
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          border: Border.all(color: _standardGold, width: 2),
                        ),
                        child: ClipOval(child: widget.profile),
                      ),
                      const SizedBox(height: 12),
                      Text(
                        widget.name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                        style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 16.5),
                      ),
                      const SizedBox(height: 12),
                      _info(Icons.domain_outlined, widget.campus),
                      const SizedBox(height: 7),
                      _info(Icons.account_balance_outlined, widget.school),
                      const SizedBox(height: 7),
                      _info(Icons.account_tree_outlined, widget.department),
                      const Spacer(),
                      Container(height: 1, color: const Color(0xFFE7ECE8)),
                      const SizedBox(height: 11),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.flag_outlined, size: 17, color: _hovered ? _standardGold : _darkGreen),
                          const SizedBox(width: 7),
                          Text(
                            'REPORT LECTURER',
                            style: TextStyle(
                              color: _hovered ? _standardGold : _darkGreen,
                              fontWeight: FontWeight.w900,
                              fontSize: 11,
                              letterSpacing: 0.8,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _info(IconData icon, String value) {
    return Row(
      children: [
        Icon(icon, size: 15, color: _standardGold),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            value,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(color: Color(0xFF647269), fontSize: 12, fontWeight: FontWeight.w500),
          ),
        ),
      ],
    );
  }
}

class _LecturerReportDialog extends StatefulWidget {
  final Map<String, dynamic> lecturer;
  final Widget profile;
  final String lecturerName;
  final String campus;
  final String school;
  final String department;

  const _LecturerReportDialog({
    required this.lecturer,
    required this.profile,
    required this.lecturerName,
    required this.campus,
    required this.school,
    required this.department,
  });

  @override
  State<_LecturerReportDialog> createState() => _LecturerReportDialogState();
}

class _LecturerReportDialogState extends State<_LecturerReportDialog> {
  final _formKey = GlobalKey<FormState>();
  final _reporterName = TextEditingController();
  final _reporterEmail = TextEditingController();
  final _reporterPhone = TextEditingController();
  final _subject = TextEditingController();
  final _description = TextEditingController();

  Map<String, dynamic>? _reporterUser;
  bool _loadingReporter = true;
  String? _reporterLoadError;

  final List<String> _categories = const [
    'Professional Conduct',
    'Attendance / Punctuality',
    'Teaching Conduct',
    'Communication',
    'Student Welfare',
    'Policy / Procedure',
    'Other',
  ];

  String _category = 'Professional Conduct';
  DateTime _incidentDate = DateTime.now();
  bool _confidential = true;
  bool _submitting = false;
  String? _error;

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

  String _accountText(Map<String, dynamic> user, List<String> keys) {
    for (final key in keys) {
      final value = user[key]?.toString().trim() ?? '';
      if (value.isNotEmpty && value.toLowerCase() != 'null') return value;
    }
    return '';
  }

  Future<void> _loadReporterAccount() async {
    if (!mounted) return;
    setState(() {
      _loadingReporter = true;
      _reporterLoadError = null;
    });

    try {
      final user = await ApiClient.getCurrentLoggedInUser();
      if (!mounted) return;

      final fullName = _accountText(user, const ['full_name', 'name']);
      final email = _accountText(user, const ['email']);
      final phone = _accountText(user, const ['phone', 'phone_number', 'mobile']);

      if (fullName.isEmpty || email.isEmpty) {
        throw StateError(
          'The signed-in user record is missing a full name or email address. '
          'Update the account record before submitting a lecturer report.',
        );
      }

      _reporterName.text = fullName;
      _reporterEmail.text = email;
      _reporterPhone.text = phone;

      setState(() {
        _reporterUser = user;
        _loadingReporter = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _reporterUser = null;
        _loadingReporter = false;
        _reporterLoadError = e.toString();
      });
    }
  }

  @override
  void dispose() {
    _reporterName.dispose();
    _reporterEmail.dispose();
    _reporterPhone.dispose();
    _subject.dispose();
    _description.dispose();
    super.dispose();
  }

  String _dateString(DateTime date) =>
      '${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';

  Future<void> _pickDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _incidentDate,
      firstDate: DateTime(DateTime.now().year - 5),
      lastDate: DateTime.now(),
      builder: (context, child) => Theme(
        data: Theme.of(context).copyWith(
          colorScheme: const ColorScheme.light(primary: _darkGreen, secondary: _standardGold),
        ),
        child: child!,
      ),
    );
    if (picked != null && mounted) setState(() => _incidentDate = picked);
  }

  Future<void> _submit() async {
    if (_submitting || _loadingReporter) return;

    if (_reporterUser == null || _reporterLoadError != null) {
      setState(() => _error = 'The signed-in reporter account could not be verified. Please reload the account details and try again.');
      return;
    }

    if (!(_formKey.currentState?.validate() ?? false)) return;

    setState(() {
      _submitting = true;
      _error = null;
    });

    try {
      final id = int.tryParse(widget.lecturer['id']?.toString() ?? '');
      final payload = <String, dynamic>{
        if (id != null && id > 0) 'lecturer_id': id,
        'lecturer_name': widget.lecturerName,
        'campus': widget.campus,
        'school': widget.school,
        'department': widget.department,
        'category': _category,
        'subject': _subject.text.trim(),
        'description': _description.text.trim(),
        'incident_date': _dateString(_incidentDate),
        'confidential': _confidential,
      };

      await ApiClient.createStaffReport(payload);
      if (mounted) Navigator.of(context).pop(true);
    } catch (e) {
      if (mounted) setState(() => _error = e.toString());
    } finally {
      if (mounted) setState(() => _submitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: !_submitting,
      child: Dialog(
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
        backgroundColor: Colors.white,
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: 780,
            maxHeight: MediaQuery.of(context).size.height * 0.92,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _header(),
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(28),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        _lecturerSummary(),
                        const SizedBox(height: 28),
                        _sectionTitle('Reporter Information'),
                        const SizedBox(height: 8),
                        const Text(
                          'These details are retrieved automatically from the account currently signed in and cannot be edited here.',
                          style: TextStyle(color: Color(0xFF718078), fontSize: 12.5, height: 1.4),
                        ),
                        const SizedBox(height: 14),
                        if (_loadingReporter)
                          _reporterLoadingPanel()
                        else if (_reporterLoadError != null)
                          _reporterErrorPanel()
                        else ...[
                          LayoutBuilder(
                            builder: (context, box) {
                              if (box.maxWidth < 600) {
                                return Column(
                                  children: [
                                    _field(
                                      _reporterName,
                                      'Full Name',
                                      Icons.person_outline,
                                      required: true,
                                      readOnly: true,
                                    ),
                                    const SizedBox(height: 14),
                                    _field(
                                      _reporterEmail,
                                      'Email Address',
                                      Icons.email_outlined,
                                      email: true,
                                      required: true,
                                      readOnly: true,
                                    ),
                                  ],
                                );
                              }
                              return Row(
                                children: [
                                  Expanded(
                                    child: _field(
                                      _reporterName,
                                      'Full Name',
                                      Icons.person_outline,
                                      required: true,
                                      readOnly: true,
                                    ),
                                  ),
                                  const SizedBox(width: 14),
                                  Expanded(
                                    child: _field(
                                      _reporterEmail,
                                      'Email Address',
                                      Icons.email_outlined,
                                      email: true,
                                      required: true,
                                      readOnly: true,
                                    ),
                                  ),
                                ],
                              );
                            },
                          ),
                          const SizedBox(height: 14),
                          _field(
                            _reporterPhone,
                            'Phone Number',
                            Icons.phone_outlined,
                            readOnly: true,
                          ),
                        ],
                        const SizedBox(height: 28),
                        _sectionTitle('Report Details'),
                        const SizedBox(height: 14),
                        LayoutBuilder(
                          builder: (context, box) {
                            final category = _categoryDropdown();
                            final date = _dateField();
                            if (box.maxWidth < 600) {
                              return Column(children: [category, const SizedBox(height: 14), date]);
                            }
                            return Row(
                              children: [
                                Expanded(child: category),
                                const SizedBox(width: 14),
                                Expanded(child: date),
                              ],
                            );
                          },
                        ),
                        const SizedBox(height: 14),
                        _field(_subject, 'Report Subject', Icons.title_rounded, required: true),
                        const SizedBox(height: 14),
                        _field(
                          _description,
                          'Describe what happened. Include specific facts, dates, locations and relevant context.',
                          Icons.notes_rounded,
                          required: true,
                          maxLines: 6,
                          minLength: 20,
                        ),
                        const SizedBox(height: 14),
                        CheckboxListTile(
                          value: _confidential,
                          onChanged: _submitting ? null : (value) => setState(() => _confidential = value ?? true),
                          contentPadding: const EdgeInsets.symmetric(horizontal: 4),
                          activeColor: _darkGreen,
                          title: const Text('Handle this report confidentially', style: TextStyle(fontWeight: FontWeight.w800, color: _ink)),
                          subtitle: const Text('Reporter contact details remain attached to the report for authorized follow-up.'),
                          controlAffinity: ListTileControlAffinity.leading,
                        ),
                        if (_error != null) ...[
                          const SizedBox(height: 12),
                          Container(
                            padding: const EdgeInsets.all(14),
                            decoration: const BoxDecoration(color: Color(0xFFFFF1F1)),
                            child: SelectableText(_error!, style: const TextStyle(color: Colors.redAccent)),
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
              ),
              _footer(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _header() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
      decoration: const BoxDecoration(
        color: _darkGreen,
        border: Border(bottom: BorderSide(color: _standardGold, width: 3)),
      ),
      child: Row(
        children: [
          const Icon(Icons.flag_outlined, color: Colors.white),
          const SizedBox(width: 12),
          const Expanded(
            child: Text(
              'REPORT LECTURER',
              style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, letterSpacing: 1.2, fontSize: 17),
            ),
          ),
          IconButton(
            onPressed: _submitting ? null : () => Navigator.of(context).pop(false),
            icon: const Icon(Icons.close_rounded, color: Colors.white),
          ),
        ],
      ),
    );
  }

  Widget _lecturerSummary() {
    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F9F8),
        border: Border.all(color: const Color(0xFFDCE3DE)),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            width: 74,
            height: 74,
            padding: const EdgeInsets.all(2),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: _standardGold, width: 2)),
            child: ClipOval(child: widget.profile),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(widget.lecturerName, style: const TextStyle(color: _ink, fontSize: 18, fontWeight: FontWeight.w900)),
                const SizedBox(height: 6),
                Text(widget.campus, style: const TextStyle(color: _darkGreen, fontWeight: FontWeight.w700)),
                const SizedBox(height: 3),
                Text('${widget.school} • ${widget.department}', maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Color(0xFF6F7F75))),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _reporterLoadingPanel() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F8F6),
        border: Border.all(color: const Color(0xFFDCE3DE)),
      ),
      child: const Row(
        children: [
          SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2, color: _darkGreen),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Text(
              'Retrieving the signed-in reporter from the database...',
              style: TextStyle(color: _ink, fontWeight: FontWeight.w700),
            ),
          ),
        ],
      ),
    );
  }

  Widget _reporterErrorPanel() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFFFF4F2),
        border: Border.all(color: const Color(0xFFF2C5BE)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(Icons.account_circle_outlined, color: Colors.redAccent, size: 21),
              SizedBox(width: 9),
              Expanded(
                child: Text(
                  'Unable to verify the signed-in reporter',
                  style: TextStyle(color: _ink, fontWeight: FontWeight.w900),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          SelectableText(
            _reporterLoadError ?? 'Unknown account error.',
            style: const TextStyle(color: Color(0xFF8C5148), height: 1.4),
          ),
          const SizedBox(height: 12),
          OutlinedButton.icon(
            onPressed: _submitting ? null : _loadReporterAccount,
            icon: const Icon(Icons.refresh_rounded, size: 18),
            label: const Text('RELOAD ACCOUNT'),
            style: OutlinedButton.styleFrom(
              foregroundColor: _darkGreen,
              side: const BorderSide(color: _darkGreen),
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
            ),
          ),
        ],
      ),
    );
  }

  Widget _sectionTitle(String title) {
    return Row(
      children: [
        Container(width: 4, height: 18, color: _standardGold),
        const SizedBox(width: 8),
        Text(title, style: const TextStyle(color: _ink, fontSize: 15.5, fontWeight: FontWeight.w900)),
      ],
    );
  }

  Widget _field(
    TextEditingController controller,
    String label,
    IconData icon, {
    bool required = false,
    bool email = false,
    bool readOnly = false,
    int maxLines = 1,
    int minLength = 0,
  }) {
    return TextFormField(
      controller: controller,
      enabled: !_submitting,
      readOnly: readOnly,
      maxLines: maxLines,
      keyboardType: email ? TextInputType.emailAddress : (maxLines > 1 ? TextInputType.multiline : TextInputType.text),
      validator: (value) {
        final text = value?.trim() ?? '';
        if (required && text.isEmpty) return 'Required';
        if (email && text.isNotEmpty && (!text.contains('@') || !text.contains('.'))) return 'Enter a valid email address';
        if (minLength > 0 && text.isNotEmpty && text.length < minLength) return 'Please provide at least $minLength characters';
        return null;
      },
      decoration: InputDecoration(
        labelText: label,
        alignLabelWithHint: maxLines > 1,
        prefixIcon: Icon(icon, color: _standardGold),
        suffixIcon: readOnly ? const Icon(Icons.lock_outline_rounded, color: Color(0xFF8A9790), size: 18) : null,
        filled: true,
        fillColor: readOnly ? const Color(0xFFF3F6F4) : Colors.white,
        border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: Color(0xFFD7DFDA)),
        ),
        focusedBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: _darkGreen, width: 2),
        ),
      ),
    );
  }

  Widget _categoryDropdown() {
    return DropdownButtonFormField<String>(
      value: _category,
      isExpanded: true,
      decoration: const InputDecoration(
        labelText: 'Report Category',
        prefixIcon: Icon(Icons.category_outlined, color: _standardGold),
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(borderRadius: BorderRadius.zero),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: Color(0xFFD7DFDA)),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.zero,
          borderSide: BorderSide(color: _darkGreen, width: 2),
        ),
      ),
      items: _categories.map((item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
      onChanged: _submitting ? null : (value) => setState(() => _category = value ?? _category),
    );
  }

  Widget _dateField() {
    return InkWell(
      onTap: _submitting ? null : _pickDate,
      child: InputDecorator(
        decoration: const InputDecoration(
          labelText: 'Incident Date',
          prefixIcon: Icon(Icons.calendar_month_outlined, color: _standardGold),
          filled: true,
          fillColor: Colors.white,
          border: OutlineInputBorder(borderRadius: BorderRadius.zero),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.zero,
            borderSide: BorderSide(color: Color(0xFFD7DFDA)),
          ),
        ),
        child: Text(_dateString(_incidentDate), style: const TextStyle(color: _ink, fontWeight: FontWeight.w600)),
      ),
    );
  }

  Widget _footer() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      decoration: const BoxDecoration(
        color: Color(0xFFF8FAF9),
        border: Border(top: BorderSide(color: Color(0xFFDCE3DE))),
      ),
      child: Wrap(
        alignment: WrapAlignment.end,
        spacing: 12,
        runSpacing: 10,
        children: [
          TextButton(
            onPressed: _submitting ? null : () => Navigator.of(context).pop(false),
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFF67736B),
              padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 18),
            ),
            child: const Text('CANCEL', style: TextStyle(fontWeight: FontWeight.w800)),
          ),
          ElevatedButton.icon(
            onPressed: (_submitting || _loadingReporter || _reporterUser == null) ? null : _submit,
            icon: _submitting
                ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                : const Icon(Icons.send_rounded, color: Colors.white, size: 19),
            label: Text(_submitting ? 'SUBMITTING...' : 'SUBMIT REPORT'),
            style: ElevatedButton.styleFrom(
              backgroundColor: _darkGreen,
              foregroundColor: Colors.white,
              elevation: 0,
              shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
            ),
          ),
        ],
      ),
    );
  }
}
