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

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

class AdminEmployeeDetailsScreen extends StatefulWidget {
  const AdminEmployeeDetailsScreen({
    super.key,
    required this.employeeId,
    required this.employeeName,
  });

  final int employeeId;
  final String employeeName;

  @override
  State<AdminEmployeeDetailsScreen> createState() => _AdminEmployeeDetailsScreenState();
}

class _AdminEmployeeDetailsScreenState extends State<AdminEmployeeDetailsScreen> {
  late Future<AdminMonthlySummary> _future;

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

  Future<AdminMonthlySummary> _load() async {
    final api = context.read<AuthService>().api;
    final data = await api.getJson('/api/v1/admin/employees/${widget.employeeId}/monthly-summary');
    final summary = data['summary'];
    if (summary is! Map<String, dynamic>) {
      throw const ApiException(statusCode: 0, message: 'استجابة غير صالحة من الخادم');
    }
    return AdminMonthlySummary.fromJson(summary);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.employeeName,
          style: const TextStyle(fontWeight: FontWeight.w900),
        ),
      ),
      body: SafeArea(
        child: FutureBuilder<AdminMonthlySummary>(
          future: _future,
          builder: (context, snapshot) {
            final isLoading = snapshot.connectionState != ConnectionState.done;
            final error = snapshot.error;
            final summary = snapshot.data;

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

            if (error != null || summary == null) {
              final message = (error is ApiException) ? error.message : 'تعذر تحميل بيانات الموظف';
              return _CenteredMessage(text: message, onRetry: _refresh);
            }

            return RefreshIndicator(
              onRefresh: _refresh,
              child: ListView(
                padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 16),
                children: [
                  Text(
                    'ملخص الشهر الحالي',
                    style: TextStyle(
                      fontWeight: FontWeight.w900,
                      color: Colors.black.withValues(alpha: 0.72),
                    ),
                  ),
                  const SizedBox(height: 10),
                  Wrap(
                    spacing: 10,
                    runSpacing: 10,
                    children: [
                      _MetricCard(title: 'عدد الغيابات (أيام)', value: summary.absentDaysTotal.toString()),
                      _MetricCard(title: 'عدد دقائق التأخير', value: summary.lateMinutesTotal.toString()),
                      _MetricCard(title: 'مجموع الخصومات', value: summary.deductionsTotal.toString()),
                      _MetricCard(title: 'مجموع المكافئات', value: summary.bonusesTotal.toString()),
                      _MetricCard(title: 'مجموع الإجازات', value: summary.leavesTotal.toString()),
                    ],
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}

class AdminMonthlySummary {
  const AdminMonthlySummary({
    required this.absentDaysTotal,
    required this.lateMinutesTotal,
    required this.deductionsTotal,
    required this.bonusesTotal,
    required this.leavesTotal,
  });

  final int absentDaysTotal;
  final int lateMinutesTotal;
  final int deductionsTotal;
  final int bonusesTotal;
  final int leavesTotal;

  static AdminMonthlySummary fromJson(Map<String, dynamic> json) {
    return AdminMonthlySummary(
      absentDaysTotal: _intOrZero(json['absent_days_total']),
      lateMinutesTotal: _intOrZero(json['late_minutes_total']),
      deductionsTotal: _intOrZero(json['deductions_total']),
      bonusesTotal: _intOrZero(json['bonuses_total']),
      leavesTotal: _intOrZero(json['leaves_total']),
    );
  }

  static int _intOrZero(dynamic value) {
    if (value is int) return value;
    if (value is num) return value.toInt();
    if (value is String) return int.tryParse(value.trim()) ?? 0;
    return 0;
  }
}

class _MetricCard extends StatelessWidget {
  const _MetricCard({
    required this.title,
    required this.value,
  });

  final String title;
  final String value;

  @override
  Widget build(BuildContext context) {
    final width = (MediaQuery.of(context).size.width - 16 - 16 - 10) / 2;
    return SizedBox(
      width: width,
      child: Card(
        elevation: 0,
        child: Padding(
          padding: const EdgeInsets.all(14),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: TextStyle(
                  fontWeight: FontWeight.w800,
                  color: Colors.black.withValues(alpha: 0.70),
                ),
              ),
              const SizedBox(height: 10),
              Text(
                value,
                style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 22),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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('تحديث'),
            ),
          ],
        ),
      ),
    );
  }
}

