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

import 'app_theme.dart';
import 'api_service.dart';
import 'auth_service.dart';
import 'leave_request_modal.dart';
import 'leaves_service.dart';

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

  @override
  State<LeavesScreen> createState() => _LeavesScreenState();
}

class _LeavesScreenState extends State<LeavesScreen> {
  LeavesService? _service;
  bool _loading = true;
  String? _error;
  bool _hasApprovedToday = false;
  int _usedPaidLeavesThisMonth = 0;
  List<LeaveDto> _leaves = const [];

  @override
  void initState() {
    super.initState();
    _service = LeavesService(api: context.read<AuthService>().api);
    _load();
  }

  Future<void> _load() async {
    if (_service == null) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final result = await _service!.index();
      if (!mounted) return;
      setState(() {
        _leaves = result.leaves;
        _hasApprovedToday = result.hasApprovedToday;
        _usedPaidLeavesThisMonth = result.usedPaidLeavesThisMonth;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = (e is ApiException)
            ? e.message
            : (e.toString().trim().isEmpty ? 'تعذر تحميل الإجازات' : e.toString().trim());
      });
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _requestLeave() async {
    if (_service == null) return;
    final remainingPaid = (3 - _usedPaidLeavesThisMonth).clamp(0, 3);
    final created = await LeaveRequestModal.show(
      context,
      service: _service!,
      remainingPaidDaysThisMonth: remainingPaid,
    );
    if (created == null) return;
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('تم إرسال طلب الإجازة'),
        backgroundColor: AppTheme.primary,
      ),
    );
    await _load();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(18),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          const Text(
            'الإجازات',
            style: TextStyle(fontWeight: FontWeight.w900, fontSize: 16),
            textAlign: TextAlign.right,
          ),
          const SizedBox(height: 12),
          SizedBox(
            height: 52,
            child: ElevatedButton.icon(
              onPressed: _loading ? null : _requestLeave,
              icon: const Icon(Icons.add),
              label: const Text('طلب إجازة', style: TextStyle(fontWeight: FontWeight.w900)),
            ),
          ),
          if (_hasApprovedToday) ...[
            const SizedBox(height: 10),
            Container(
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: const Color(0xFFE8F7EE),
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: const Color(0xFF2ECC71).withValues(alpha: 0.35)),
              ),
              child: const Text(
                'أنت مجاز لهذا اليوم',
                style: TextStyle(fontWeight: FontWeight.w900),
                textAlign: TextAlign.right,
              ),
            ),
          ],
          const SizedBox(height: 14),
          if (_error != null) ...[
            Container(
              padding: const EdgeInsets.all(14),
              decoration: BoxDecoration(
                color: Colors.red.shade50,
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: Colors.red.shade200),
              ),
              child: Text(
                _error!,
                style: TextStyle(fontWeight: FontWeight.w800, color: Colors.red.shade700),
                textAlign: TextAlign.right,
              ),
            ),
            const SizedBox(height: 12),
          ],
          Expanded(
            child: RefreshIndicator(
              onRefresh: _load,
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : (_leaves.isEmpty)
                      ? ListView(
                          children: const [
                            SizedBox(height: 60),
                            Center(
                              child: Text(
                                'لا توجد إجازات حتى الآن',
                                style: TextStyle(fontWeight: FontWeight.w800),
                              ),
                            ),
                          ],
                        )
                      : ListView.separated(
                          itemCount: _leaves.length,
                          separatorBuilder: (context, index) => const SizedBox(height: 10),
                          itemBuilder: (context, index) => _LeaveTile(leave: _leaves[index]),
                        ),
            ),
          ),
        ],
      ),
    );
  }
}

class _LeaveTile extends StatelessWidget {
  const _LeaveTile({
    required this.leave,
  });

  final LeaveDto leave;

  String _formatDate(DateTime date) {
    final local = date.toLocal();
    final y = local.year.toString().padLeft(4, '0');
    final m = local.month.toString().padLeft(2, '0');
    final d = local.day.toString().padLeft(2, '0');
    return '$y/$m/$d';
  }

  String _typeLabel() {
    return leave.leaveType == 'timed' ? 'إجازة زمنية' : 'إجازة ليوم كامل';
  }

  String _paidLabel() {
    if (leave.leaveType == 'timed') {
      return 'مدفوعة';
    }
    return leave.isPaid ? 'مدفوعة' : 'غير مدفوعة';
  }

  String _statusLabel() {
    switch (leave.status) {
      case 'approved':
        return 'مقبولة';
      case 'rejected':
        return 'مرفوضة';
      default:
        return 'قيد الانتظار';
    }
  }

  Color _statusColor() {
    switch (leave.status) {
      case 'approved':
        return const Color(0xFF16A34A);
      case 'rejected':
        return Colors.red.shade600;
      default:
        return Colors.orange.shade700;
    }
  }

  @override
  Widget build(BuildContext context) {
    final dateText = _formatDate(leave.leaveDate);
    final timeFrom = (leave.leaveType == 'timed') ? leave.leaveTimeFrom : null;
    final timeTo = (leave.leaveType == 'timed') ? leave.leaveTimeTo : null;
    final paidText = _paidLabel();
    final timeFromText = (timeFrom ?? '').trim();
    final timeToText = (timeTo ?? '').trim();
    final hasTimeRange = timeFromText.isNotEmpty && timeToText.isNotEmpty;
    final hasAnyTime = timeFromText.isNotEmpty || timeToText.isNotEmpty;
    final timeLabel = hasTimeRange
        ? '${timeFromText.length >= 5 ? timeFromText.substring(0, 5) : timeFromText} - ${timeToText.length >= 5 ? timeToText.substring(0, 5) : timeToText}'
        : (timeFromText.isNotEmpty ? (timeFromText.length >= 5 ? timeFromText.substring(0, 5) : timeFromText) : (timeToText.length >= 5 ? timeToText.substring(0, 5) : timeToText));

    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: Colors.black.withValues(alpha: 0.06)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  _typeLabel(),
                  style: const TextStyle(fontWeight: FontWeight.w900),
                  textAlign: TextAlign.right,
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.05),
                  borderRadius: BorderRadius.circular(999),
                ),
                child: Text(
                  paidText,
                  style: TextStyle(
                    fontWeight: FontWeight.w900,
                    fontSize: 11,
                    color: Colors.black.withValues(alpha: 0.75),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                decoration: BoxDecoration(
                  color: _statusColor().withValues(alpha: 0.12),
                  borderRadius: BorderRadius.circular(999),
                ),
                child: Text(
                  _statusLabel(),
                  style: TextStyle(fontWeight: FontWeight.w900, fontSize: 11, color: _statusColor()),
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              const Icon(Icons.calendar_month, size: 18),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  dateText,
                  style: const TextStyle(fontWeight: FontWeight.w900),
                  textAlign: TextAlign.right,
                ),
              ),
              if (hasAnyTime) ...[
                const SizedBox(width: 10),
                const Icon(Icons.schedule, size: 18),
                const SizedBox(width: 8),
                Text(
                  timeLabel,
                  style: const TextStyle(fontWeight: FontWeight.w900),
                ),
              ],
            ],
          ),
          if (leave.reason != null && leave.reason!.trim().isNotEmpty) ...[
            const SizedBox(height: 10),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: AppTheme.surfaceAlt,
                borderRadius: BorderRadius.circular(14),
              ),
              child: Text(
                leave.reason!.trim(),
                style: TextStyle(
                  fontWeight: FontWeight.w800,
                  color: Colors.black.withValues(alpha: 0.75),
                  height: 1.35,
                ),
                textAlign: TextAlign.right,
              ),
            ),
          ],
        ],
      ),
    );
  }
}
