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

import 'api_service.dart';
import 'auth_service.dart';

class AdminLeavesScreen extends StatefulWidget {
  const AdminLeavesScreen({super.key});

  @override
  State<AdminLeavesScreen> createState() => _AdminLeavesScreenState();
}

class _AdminLeavesScreenState extends State<AdminLeavesScreen> {
  late Future<List<AdminLeaveItem>> _future;
  final Set<int> _processingIds = <int>{};

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

  Future<List<AdminLeaveItem>> _load() async {
    final api = context.read<AuthService>().api;
    final data = await api.getJson('/api/v1/admin/leaves?status=all');
    final items = data['leaves'];
    if (items is! List) return <AdminLeaveItem>[];
    return items.whereType<Map<String, dynamic>>().map(AdminLeaveItem.fromJson).toList();
  }

  Future<void> _refresh() async {
    setState(() => _future = _load());
    await _future;
  }

  Future<void> _act({
    required int leaveId,
    required String action,
  }) async {
    if (_processingIds.contains(leaveId)) return;
    setState(() => _processingIds.add(leaveId));

    final api = context.read<AuthService>().api;
    try {
      await api.postJson('/api/v1/admin/leaves/$leaveId/$action', body: {});
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(action == 'approve' ? 'تمت الموافقة' : 'تم الرفض')),
      );
      await _refresh();
    } on ApiException catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));
    } catch (_) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('حدث خطأ غير متوقع')));
    } finally {
      if (mounted) {
        setState(() => _processingIds.remove(leaveId));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<AdminLeaveItem>>(
      future: _future,
      builder: (context, snapshot) {
        final isLoading = snapshot.connectionState != ConnectionState.done;
        final error = snapshot.error;
        final items = snapshot.data ?? const <AdminLeaveItem>[];

        if (isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (error != null) {
          final message = (error is ApiException) ? error.message : 'تعذر تحميل الإجازات';
          return _CenteredMessage(text: message, onRetry: _refresh);
        }

        if (items.isEmpty) {
          return _CenteredMessage(text: 'لا توجد طلبات إجازة حالياً', onRetry: _refresh);
        }

        return RefreshIndicator(
          onRefresh: _refresh,
          child: ListView.separated(
            padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 16),
            itemCount: items.length,
            separatorBuilder: (context, index) => const SizedBox(height: 10),
            itemBuilder: (context, index) {
              final item = items[index];
              final typeLabel = item.leaveType == 'timed'
                  ? 'إجازة زمنية'
                  : item.leaveType == 'full_day'
                      ? 'إجازة يوم'
                      : item.leaveType;
              final date = _formatDateOnly(item.leaveDate.toLocal());
              final statusLabel = _statusLabel(item.status);
              final isPending = item.status == 'pending';
              final isBusy = _processingIds.contains(item.id);
              String shortTime(String raw) {
                final t = raw.trim();
                return t.length >= 5 ? t.substring(0, 5) : t;
              }

              final lines = <String>[
                typeLabel,
                if (item.leaveType == 'full_day') (item.isPaid ? 'مدفوعة' : 'غير مدفوعة'),
                'التاريخ: $date',
                if (item.leaveType == 'timed') ...[
                  if ((item.leaveTimeFrom ?? '').trim().isNotEmpty && (item.leaveTimeTo ?? '').trim().isNotEmpty)
                    'الوقت: ${shortTime(item.leaveTimeFrom!)} - ${shortTime(item.leaveTimeTo!)}'
                  else if ((item.leaveTimeFrom ?? '').trim().isNotEmpty)
                    'الوقت: ${shortTime(item.leaveTimeFrom!)}'
                  else if ((item.leaveTimeTo ?? '').trim().isNotEmpty)
                    'الوقت: ${shortTime(item.leaveTimeTo!)}'
                  else if ((item.leaveTime ?? '').trim().isNotEmpty)
                    'الوقت: ${shortTime(item.leaveTime!)}',
                ] else if ((item.leaveTime ?? '').trim().isNotEmpty)
                  'الوقت: ${shortTime(item.leaveTime!)}',
                if ((item.reason ?? '').trim().isNotEmpty) 'السبب: ${item.reason!.trim()}',
              ];

              return Card(
                elevation: 0,
                child: Padding(
                  padding: const EdgeInsets.all(14),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              item.employeeName,
                              style: const TextStyle(fontWeight: FontWeight.w900),
                            ),
                          ),
                          _StatusChip(text: statusLabel, status: item.status),
                        ],
                      ),
                      const SizedBox(height: 10),
                      for (final line in lines)
                        Padding(
                          padding: const EdgeInsets.only(bottom: 6),
                          child: Text(
                            line,
                            style: TextStyle(
                              fontWeight: FontWeight.w600,
                              color: Colors.black.withValues(alpha: 0.70),
                            ),
                          ),
                        ),
                      if (isPending) ...[
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            Expanded(
                              child: ElevatedButton(
                                onPressed: isBusy ? null : () => _act(leaveId: item.id, action: 'approve'),
                                child: isBusy
                                    ? const SizedBox(
                                        height: 18,
                                        width: 18,
                                        child: CircularProgressIndicator(
                                          strokeWidth: 2.4,
                                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                        ),
                                      )
                                    : const Text(
                                        'موافقة',
                                        style: TextStyle(fontWeight: FontWeight.w900),
                                      ),
                              ),
                            ),
                            const SizedBox(width: 10),
                            Expanded(
                              child: OutlinedButton(
                                onPressed: isBusy ? null : () => _act(leaveId: item.id, action: 'reject'),
                                child: const Text(
                                  'رفض',
                                  style: TextStyle(fontWeight: FontWeight.w900),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  String _formatDateOnly(DateTime dt) {
    final y = dt.year.toString().padLeft(4, '0');
    final m = dt.month.toString().padLeft(2, '0');
    final d = dt.day.toString().padLeft(2, '0');
    return '$y-$m-$d';
  }

  String _statusLabel(String status) {
    switch (status) {
      case 'pending':
        return 'قيد المراجعة';
      case 'approved':
        return 'موافق عليها';
      case 'rejected':
        return 'مرفوضة';
      default:
        return status;
    }
  }
}

class AdminLeaveItem {
  const AdminLeaveItem({
    required this.id,
    required this.employeeName,
    required this.leaveType,
    required this.isPaid,
    required this.leaveDate,
    required this.leaveTime,
    required this.leaveTimeFrom,
    required this.leaveTimeTo,
    required this.reason,
    required this.status,
  });

  final int id;
  final String employeeName;
  final String leaveType;
  final bool isPaid;
  final DateTime leaveDate;
  final String? leaveTime;
  final String? leaveTimeFrom;
  final String? leaveTimeTo;
  final String? reason;
  final String status;

  static AdminLeaveItem fromJson(Map<String, dynamic> json) {
    final id = json['id'];
    final employeeName = json['employee_name'];
    final leaveType = json['leave_type'];
    final leaveDateRaw = json['leave_date'];
    final status = json['status'];

    if (id is! int || employeeName is! String || leaveType is! String || leaveDateRaw is! String || status is! String) {
      throw const ApiException(statusCode: 0, message: 'استجابة غير صالحة من الخادم');
    }

    final leaveDate = DateTime.tryParse(leaveDateRaw);
    if (leaveDate == null) {
      throw const ApiException(statusCode: 0, message: 'استجابة غير صالحة من الخادم');
    }

    return AdminLeaveItem(
      id: id,
      employeeName: employeeName.trim().isEmpty ? '—' : employeeName,
      leaveType: leaveType,
      isPaid: json['is_paid'] == true,
      leaveDate: leaveDate,
      leaveTime: json['leave_time'] is String ? json['leave_time'] as String : null,
      leaveTimeFrom: json['leave_time_from'] is String
          ? json['leave_time_from'] as String
          : (json['leave_time'] is String ? json['leave_time'] as String : null),
      leaveTimeTo: json['leave_time_to'] is String ? json['leave_time_to'] as String : null,
      reason: json['reason'] is String ? json['reason'] as String : null,
      status: status,
    );
  }
}

class _StatusChip extends StatelessWidget {
  const _StatusChip({required this.text, required this.status});

  final String text;
  final String status;

  @override
  Widget build(BuildContext context) {
    Color bgColor = Colors.black.withValues(alpha: 0.05);
    Color textColor = Colors.black.withValues(alpha: 0.70);

    if (status == 'approved') {
      bgColor = Colors.green.withValues(alpha: 0.15);
      textColor = Colors.green.shade800;
    } else if (status == 'rejected') {
      bgColor = Colors.red.withValues(alpha: 0.15);
      textColor = Colors.red.shade800;
    } else if (status == 'pending') {
      bgColor = Colors.orange.withValues(alpha: 0.15);
      textColor = Colors.orange.shade900;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w800,
          color: textColor,
          fontSize: 12,
        ),
      ),
    );
  }
}

class _CenteredMessage extends StatelessWidget {
  const _CenteredMessage({
    required this.text,
    required this.onRetry,
  });

  final String text;
  final Future<void> Function() onRetry;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(18),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              text,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontWeight: FontWeight.w700,
                color: Colors.black.withValues(alpha: 0.65),
              ),
            ),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: onRetry,
              child: const Text('تحديث'),
            ),
          ],
        ),
      ),
    );
  }
}
