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

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

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

  @override
  State<AdminEmployeesScreen> createState() => _AdminEmployeesScreenState();
}

class _AdminEmployeesScreenState extends State<AdminEmployeesScreen> {
  late Future<List<AdminEmployeeItem>> _future;

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

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

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

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

        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 avatar = (item.avatarUrl ?? '').trim();
              final resolvedUrl = avatar.startsWith('/') ? '${ApiService.defaultBaseUrl}$avatar' : avatar;
              final subtitleParts = <String>[
                if ((item.roleName ?? '').trim().isNotEmpty) item.roleName!.trim(),
                if ((item.phone ?? '').trim().isNotEmpty) item.phone!.trim(),
              ];

              return Card(
                elevation: 0,
                child: ListTile(
                  leading: _CircleImage(url: resolvedUrl),
                  title: Text(
                    item.fullName,
                    style: const TextStyle(fontWeight: FontWeight.w800),
                  ),
                  subtitle: subtitleParts.isEmpty ? null : Text(subtitleParts.join(' • ')),
                  trailing: const Icon(Icons.chevron_right),
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => AdminEmployeeDetailsScreen(
                          employeeId: item.id,
                          employeeName: item.fullName,
                        ),
                      ),
                    );
                  },
                ),
              );
            },
          ),
        );
      },
    );
  }
}

class AdminEmployeeItem {
  const AdminEmployeeItem({
    required this.id,
    required this.fullName,
    required this.phone,
    required this.roleName,
    required this.avatarUrl,
  });

  final int id;
  final String fullName;
  final String? phone;
  final String? roleName;
  final String? avatarUrl;

  static AdminEmployeeItem fromJson(Map<String, dynamic> json) {
    final id = json['id'];
    final fullName = json['full_name'];
    if (id is! int || fullName is! String) {
      throw const ApiException(statusCode: 0, message: 'استجابة غير صالحة من الخادم');
    }

    return AdminEmployeeItem(
      id: id,
      fullName: fullName.trim().isEmpty ? '—' : fullName,
      phone: json['phone'] is String ? json['phone'] as String : null,
      roleName: json['role_name'] is String ? json['role_name'] as String : null,
      avatarUrl: json['avatar_url'] is String ? json['avatar_url'] as String : null,
    );
  }
}

class _CircleImage extends StatelessWidget {
  const _CircleImage({required this.url});

  final String url;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 44,
      height: 44,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Colors.black.withValues(alpha: 0.05),
      ),
      child: ClipOval(
        child: url.isEmpty
            ? const Icon(Icons.person_outline)
            : Image.network(
                url,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) => const Icon(Icons.person_outline),
              ),
      ),
    );
  }
}

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