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

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

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

  @override
  State<SalaryScreen> createState() => _SalaryScreenState();
}

class _SalaryScreenState extends State<SalaryScreen> {
  DateTime _selectedDate = DateTime.now();
  bool _loading = true;
  String? _error;
  _ReportSummary? _summary;

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

  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';
  }

  Future<void> _pickDate() async {
    final now = DateTime.now();
    final picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(now.year - 2),
      lastDate: DateTime(now.year + 2),
      locale: const Locale('ar'),
    );
    if (picked == null) return;
    setState(() {
      _selectedDate = picked;
    });
    await _load();
  }

  Future<void> _load() async {
    final api = context.read<AuthService>().api;
    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final date = _formatDate(_selectedDate);
      final data = await api.getJson('/api/v1/reports/summary?date=$date');
      setState(() {
        _summary = _ReportSummary.fromJson(data);
      });
    } on ApiException catch (e) {
      setState(() => _error = e.message);
    } catch (_) {
      setState(() => _error = 'تعذر تحميل التقارير');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final month = _summary?.month ?? '—';

    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),
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(18),
              border: Border.all(color: AppTheme.primary.withValues(alpha: 0.14)),
            ),
            child: Row(
              children: [
                Expanded(
                  child: _FilterField(
                    label: 'اختر اليوم',
                    value: _formatDate(_selectedDate),
                    icon: Icons.calendar_month,
                    onTap: _pickDate,
                  ),
                ),
                const SizedBox(width: 12),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  decoration: BoxDecoration(
                    color: AppTheme.surfaceAlt,
                    borderRadius: BorderRadius.circular(14),
                  ),
                  child: Text(
                    'شهر: $month',
                    style: TextStyle(
                      fontWeight: FontWeight.w900,
                      color: Colors.black.withValues(alpha: 0.72),
                    ),
                  ),
                ),
              ],
            ),
          ),
          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())
                  : ListView(
                      children: [
                        const SizedBox(height: 4),
                        const Text(
                          'ملخص هذا الشهر',
                          style: TextStyle(fontWeight: FontWeight.w900),
                          textAlign: TextAlign.right,
                        ),
                        const SizedBox(height: 10),
                        Wrap(
                          spacing: 10,
                          runSpacing: 10,
                          children: [
                            _StatCard(
                              label: 'عدد دقائق التأخير',
                              value: '${_summary?.monthLateMinutes ?? 0}',
                            ),
                            _StatCard(
                              label: 'مجموع مبلغ التأخير',
                              value: '${_summary?.monthLateAmount ?? 0}',
                            ),
                            _StatCard(
                              label: 'عدد الاجازات',
                              value: '${_summary?.monthFullDayLeaves ?? 0}',
                            ),
                            _StatCard(
                              label: 'عدد الزمنيات',
                              value: '${_summary?.monthTimedLeaves ?? 0}',
                            ),
                          ],
                        ),
                        const SizedBox(height: 18),
                        const Text(
                          'بيانات اليوم المختار',
                          style: TextStyle(fontWeight: FontWeight.w900),
                          textAlign: TextAlign.right,
                        ),
                        const SizedBox(height: 10),
                        Wrap(
                          spacing: 10,
                          runSpacing: 10,
                          children: [
                            _StatCard(
                              label: 'دقائق التأخير اليوم',
                              value: '${_summary?.dayLateMinutes ?? 0}',
                            ),
                            _StatCard(
                              label: 'مبلغ التأخير اليوم',
                              value: '${_summary?.dayLateAmount ?? 0}',
                            ),
                            _StatCard(
                              label: 'اجازات اليوم',
                              value: '${_summary?.dayFullDayLeaves ?? 0}',
                            ),
                            _StatCard(
                              label: 'زمنيات اليوم',
                              value: '${_summary?.dayTimedLeaves ?? 0}',
                            ),
                          ],
                        ),
                        const SizedBox(height: 30),
                      ],
                    ),
            ),
          ),
        ],
      ),
    );
  }
}

class _FilterField extends StatelessWidget {
  const _FilterField({
    required this.label,
    required this.value,
    required this.icon,
    required this.onTap,
  });

  final String label;
  final String value;
  final IconData icon;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(14),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        decoration: BoxDecoration(
          color: AppTheme.surfaceAlt,
          borderRadius: BorderRadius.circular(14),
        ),
        child: Row(
          children: [
            Icon(icon, color: Colors.black.withValues(alpha: 0.7), size: 18),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    label,
                    style: TextStyle(
                      fontWeight: FontWeight.w800,
                      fontSize: 11,
                      color: Colors.black.withValues(alpha: 0.62),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    value,
                    style: const TextStyle(fontWeight: FontWeight.w900),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _StatCard extends StatelessWidget {
  const _StatCard({
    required this.label,
    required this.value,
  });

  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    final width = (MediaQuery.of(context).size.width - 18 * 2 - 10) / 2;
    return SizedBox(
      width: width,
      child: Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(18),
          border: Border.all(color: AppTheme.primary.withValues(alpha: 0.12)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              label,
              style: TextStyle(
                fontWeight: FontWeight.w800,
                fontSize: 12,
                color: Colors.black.withValues(alpha: 0.68),
              ),
            ),
            const SizedBox(height: 10),
            Text(
              value,
              style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

class _ReportSummary {
  _ReportSummary({
    required this.month,
    required this.selectedDate,
    required this.monthLateMinutes,
    required this.monthLateAmount,
    required this.monthFullDayLeaves,
    required this.monthTimedLeaves,
    required this.dayLateMinutes,
    required this.dayLateAmount,
    required this.dayFullDayLeaves,
    required this.dayTimedLeaves,
  });

  final String month;
  final String selectedDate;
  final int monthLateMinutes;
  final int monthLateAmount;
  final int monthFullDayLeaves;
  final int monthTimedLeaves;
  final int dayLateMinutes;
  final int dayLateAmount;
  final int dayFullDayLeaves;
  final int dayTimedLeaves;

  factory _ReportSummary.fromJson(Map<String, dynamic> json) {
    int asInt(dynamic v) => (v is num) ? v.toInt() : int.tryParse('${v ?? ''}'.trim()) ?? 0;
    String asStr(dynamic v) => (v is String) ? v : '${v ?? ''}'.trim();
    return _ReportSummary(
      month: asStr(json['month']).isEmpty ? '—' : asStr(json['month']),
      selectedDate: asStr(json['selected_date']),
      monthLateMinutes: asInt(json['month_late_minutes']),
      monthLateAmount: asInt(json['month_late_amount']),
      monthFullDayLeaves: asInt(json['month_full_day_leaves']),
      monthTimedLeaves: asInt(json['month_timed_leaves']),
      dayLateMinutes: asInt(json['day_late_minutes']),
      dayLateAmount: asInt(json['day_late_amount']),
      dayFullDayLeaves: asInt(json['day_full_day_leaves']),
      dayTimedLeaves: asInt(json['day_timed_leaves']),
    );
  }
}
