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

import '../../../../core/services/request_workflow_service.dart';
import 'pending_requests_sub_tab.dart' show RequestWorkflowDetailDialog;

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

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

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

  @override
  State<ProcessedRequestsSubTab> createState() => _ProcessedRequestsSubTabState();
}

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

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

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

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

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

  int _count(String status) => _requests.where((r) => '${r['status']}'.toLowerCase() == status).length;

  Future<void> _open(Map<String, dynamic> request) async {
    await showDialog<bool>(
      context: context,
      barrierDismissible: true,
      builder: (_) => RequestWorkflowDetailDialog(request: request, readOnly: true),
    );
  }

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

    return RefreshIndicator(
      onRefresh: _load,
      color: _green,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 650;
          final horizontal = constraints.maxWidth >= 1000 ? 28.0 : (compact ? 12.0 : 18.0);
          final list = _visible;
          final grouped = <String, List<Map<String, dynamic>>>{};
          for (final row in list) {
            final campus = '${row['target_campus'] ?? 'Unassigned Campus'}'.trim();
            grouped.putIfAbsent(campus.isEmpty ? 'Unassigned Campus' : campus, () => []).add(row);
          }

          return ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: EdgeInsets.fromLTRB(horizontal, 10, horizontal, 100),
            children: [
              _ArchiveToolbar(
                compact: compact,
                controller: _search,
                status: _status,
                approved: _count('approved'),
                declined: _count('declined'),
                cancelled: _count('cancelled'),
                onStatus: (value) => setState(() => _status = value),
                onRefresh: _load,
              ),
              const SizedBox(height: 14),
              if (list.isEmpty)
                const _ArchiveEmpty()
              else
                ...grouped.entries.expand((entry) sync* {
                  yield _CampusHeading(campus: entry.key, count: entry.value.length);
                  yield const SizedBox(height: 8);
                  for (final request in entry.value) {
                    yield Padding(
                      padding: const EdgeInsets.only(bottom: 9),
                      child: _ProcessedCard(request: request, compact: compact, onOpen: () => _open(request)),
                    );
                  }
                  yield const SizedBox(height: 10);
                }),
            ],
          );
        },
      ),
    );
  }
}

class _ArchiveToolbar extends StatelessWidget {
  final bool compact;
  final TextEditingController controller;
  final String status;
  final int approved;
  final int declined;
  final int cancelled;
  final ValueChanged<String> onStatus;
  final VoidCallback onRefresh;

  const _ArchiveToolbar({
    required this.compact,
    required this.controller,
    required this.status,
    required this.approved,
    required this.declined,
    required this.cancelled,
    required this.onStatus,
    required this.onRefresh,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(compact ? 13 : 16),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(15), border: Border.all(color: _border)),
      child: Column(
        children: [
          Row(
            children: [
              const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Processed archive', style: TextStyle(fontSize: 17, color: _ink, fontWeight: FontWeight.w900)), SizedBox(height: 3), Text('Final decisions and permanent routing history available to participants.', style: TextStyle(color: _muted, fontSize: 11.5))])),
              IconButton(onPressed: onRefresh, tooltip: 'Refresh', icon: const Icon(Icons.refresh_rounded, color: _green)),
            ],
          ),
          const SizedBox(height: 12),
          TextField(
            controller: controller,
            decoration: InputDecoration(
              hintText: 'Search archive...',
              prefixIcon: const Icon(Icons.search_rounded, size: 20),
              suffixIcon: controller.text.isEmpty ? null : IconButton(onPressed: controller.clear, icon: const Icon(Icons.close_rounded, size: 18)),
              filled: true,
              fillColor: _surface,
              isDense: true,
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
              enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
              focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _gold, width: 1.4)),
            ),
          ),
          const SizedBox(height: 10),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                _StatusFilter(label: 'All', selected: status == 'all', onTap: () => onStatus('all')),
                const SizedBox(width: 7),
                _StatusFilter(label: 'Approved $approved', selected: status == 'approved', color: _green, onTap: () => onStatus('approved')),
                const SizedBox(width: 7),
                _StatusFilter(label: 'Declined $declined', selected: status == 'declined', color: Colors.red.shade700, onTap: () => onStatus('declined')),
                const SizedBox(width: 7),
                _StatusFilter(label: 'Cancelled $cancelled', selected: status == 'cancelled', color: _muted, onTap: () => onStatus('cancelled')),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

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

class _CampusHeading extends StatelessWidget {
  final String campus;
  final int count;
  const _CampusHeading({required this.campus, required this.count});
  @override
  Widget build(BuildContext context) {
    return Row(children: [Container(width: 34, height: 34, decoration: BoxDecoration(color: _green.withOpacity(0.07), borderRadius: BorderRadius.circular(10)), child: const Icon(Icons.location_city_rounded, color: _green, size: 18)), const SizedBox(width: 10), Expanded(child: Text(campus.toUpperCase(), style: const TextStyle(color: _ink, fontSize: 11, fontWeight: FontWeight.w900, letterSpacing: 0.7))), Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), decoration: BoxDecoration(color: _surface, borderRadius: BorderRadius.circular(20), border: Border.all(color: _border)), child: Text('$count records', style: const TextStyle(fontSize: 9.5, color: _muted, fontWeight: FontWeight.w800)))]);
  }
}

class _ProcessedCard extends StatelessWidget {
  final Map<String, dynamic> request;
  final bool compact;
  final VoidCallback onOpen;
  const _ProcessedCard({required this.request, required this.compact, required this.onOpen});

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

  @override
  Widget build(BuildContext context) {
    final status = '${request['status'] ?? ''}'.toLowerCase();
    final approved = status == 'approved';
    final cancelled = status == 'cancelled';
    final color = approved ? _green : cancelled ? _muted : Colors.red.shade700;
    final icon = approved ? Icons.verified_rounded : cancelled ? Icons.remove_circle_outline_rounded : Icons.cancel_rounded;
    final label = status.isEmpty ? 'PROCESSED' : status.toUpperCase();

    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(14),
      child: InkWell(
        onTap: onOpen,
        borderRadius: BorderRadius.circular(14),
        child: Container(
          padding: EdgeInsets.all(compact ? 14 : 16),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
          child: Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(width: 42, height: 42, decoration: BoxDecoration(color: color.withOpacity(0.08), borderRadius: BorderRadius.circular(12)), child: Icon(icon, color: color, size: 21)),
                  const SizedBox(width: 12),
                  Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('${request['reference'] ?? 'Untitled request'}', maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 14)), const SizedBox(height: 4), Text('${request['requester_name'] ?? 'Staff'} → ${request['recipient_position'] ?? 'Office'}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 11.2, fontWeight: FontWeight.w600))])),
                  Container(padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5), decoration: BoxDecoration(color: color.withOpacity(0.08), borderRadius: BorderRadius.circular(20)), child: Text(label, style: TextStyle(color: color, fontSize: 9, fontWeight: FontWeight.w900, letterSpacing: 0.5))),
                ],
              ),
              const SizedBox(height: 12),
              Row(children: [const Icon(Icons.schedule_rounded, size: 14, color: _muted), const SizedBox(width: 5), Expanded(child: Text(_date(request['finalized_at'] ?? request['updated_at']), style: const TextStyle(color: _muted, fontSize: 10.5))), OutlinedButton.icon(onPressed: onOpen, style: OutlinedButton.styleFrom(foregroundColor: color, side: BorderSide(color: color.withOpacity(0.25)), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9))), icon: const Icon(Icons.history_edu_rounded, size: 15), label: const Text('OPEN RECORD', style: TextStyle(fontSize: 9.5, fontWeight: FontWeight.w900)))]),
            ],
          ),
        ),
      ),
    );
  }
}

class _ArchiveEmpty extends StatelessWidget {
  const _ArchiveEmpty();
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 54),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), border: Border.all(color: _border)),
      child: Column(children: [Container(width: 68, height: 68, decoration: BoxDecoration(color: _green.withOpacity(0.06), shape: BoxShape.circle), child: const Icon(Icons.inventory_2_outlined, color: _green, size: 32)), const SizedBox(height: 14), const Text('No processed records', style: TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 17)), const SizedBox(height: 6), const Text('Approved, declined and cancelled requests that you are entitled to view will appear here.', textAlign: TextAlign.center, style: TextStyle(color: _muted, fontSize: 12, height: 1.4))]),
    );
  }
}

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