import 'dart:async';

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

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

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

  @override
  State<AdminAttendanceLogScreen> createState() => _AdminAttendanceLogScreenState();
}

class _AdminAttendanceLogScreenState extends State<AdminAttendanceLogScreen> {
  late Future<List<AdminAttendanceLogItem>> _future;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _future = _load();
    _timer = Timer.periodic(const Duration(seconds: 20), (_) {
      if (!mounted) return;
      setState(() => _future = _load());
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

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

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

  Future<void> _openLocation(double latitude, double longitude) async {
    final geoUri = Uri.parse('geo:$latitude,$longitude?q=$latitude,$longitude');
    final webUri = Uri.parse('https://www.google.com/maps/search/?api=1&query=$latitude,$longitude');

    final geoOk = await launchUrl(
      geoUri,
      mode: LaunchMode.externalApplication,
    );
    if (geoOk) return;

    final webOk = await launchUrl(
      webUri,
      mode: LaunchMode.externalApplication,
    );
    if (webOk) return;

    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('تعذر فتح تطبيق الخرائط على هذا الجهاز')),
    );
  }

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

        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.type == 'check_in' ? 'حضور' : item.type == 'check_out' ? 'انصراف' : item.type;
              final dt = item.loggedAt.toLocal();
              final date = _formatDateOnly(dt);
              final time = _formatTime(dt);
              final subtitle = '$typeLabel • $date • $time';
              final imageUrl = (item.imageUrl ?? '').trim();
              final resolvedImageUrl =
                  imageUrl.startsWith('/') ? '${ApiService.defaultBaseUrl}$imageUrl' : imageUrl;

              return Card(
                elevation: 0,
                child: ListTile(
                  leading: _CircleImage(url: resolvedImageUrl),
                  title: Text(
                    item.employeeName,
                    style: const TextStyle(fontWeight: FontWeight.w800),
                  ),
                  subtitle: Text(subtitle),
                  trailing: item.latitude != null && item.longitude != null
                      ? IconButton(
                          icon: const Icon(Icons.location_on, color: Colors.red),
                          onPressed: () => _openLocation(item.latitude!, item.longitude!),
                        )
                      : null,
                ),
              );
            },
          ),
        );
      },
    );
  }

  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 _formatTime(DateTime dt) {
    final h = dt.hour.toString().padLeft(2, '0');
    final m = dt.minute.toString().padLeft(2, '0');
    return '$h:$m';
  }
}

class AdminAttendanceLogItem {
  AdminAttendanceLogItem({
    required this.id,
    required this.employeeName,
    required this.type,
    required this.loggedAt,
    required this.imageUrl,
    required this.latitude,
    required this.longitude,
  });

  final int id;
  final String employeeName;
  final String type;
  final DateTime loggedAt;
  final String? imageUrl;
  final double? latitude;
  final double? longitude;

  static AdminAttendanceLogItem fromJson(Map<String, dynamic> json) {
    final id = json['id'];
    final employeeName = json['employee_name'];
    final type = json['type'];
    final loggedAtRaw = json['logged_at'];

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

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

    return AdminAttendanceLogItem(
      id: id,
      employeeName: employeeName.trim().isEmpty ? '—' : employeeName,
      type: type,
      loggedAt: loggedAt,
      imageUrl: json['image_url'] is String ? json['image_url'] as String : null,
      latitude: _doubleOrNull(json['latitude']),
      longitude: _doubleOrNull(json['longitude']),
    );
  }

  static double? _doubleOrNull(dynamic value) {
    if (value is double) return value;
    if (value is num) return value.toDouble();
    if (value is String) return double.tryParse(value.trim());
    return null;
  }
}

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

  final String url;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (url.isEmpty) return;
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Scaffold(
              appBar: AppBar(
                backgroundColor: Colors.black,
                iconTheme: const IconThemeData(color: Colors.white),
              ),
              backgroundColor: Colors.black,
              body: Center(
                child: InteractiveViewer(
                  child: Image.network(
                    url,
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) => const Icon(Icons.error, color: Colors.white),
                  ),
                ),
              ),
            ),
          ),
        );
      },
      child: 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('تحديث'),
            ),
          ],
        ),
      ),
    );
  }
}
