import 'package:flutter/material.dart';
import 'package:sefer_admin1/constant/colors.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';

class ErrorLog {
  final String id;
  final String error;
  final String userId;
  final String userType;
  final String phone;
  final String createdAt;
  final String device;
  final String details;
  final String status;

  ErrorLog({
    required this.id,
    required this.error,
    required this.userId,
    required this.userType,
    required this.phone,
    required this.createdAt,
    required this.device,
    required this.details,
    required this.status,
  });

  factory ErrorLog.fromJson(Map<String, dynamic> j) => ErrorLog(
        id: (j['id'] ?? '').toString(),
        error: (j['error'] ?? '').toString(),
        userId: (j['userId'] ?? '').toString(),
        userType: (j['userType'] ?? '').toString(),
        phone: (j['phone'] ?? '').toString(),
        createdAt: (j['created_at'] ?? '').toString(),
        device: (j['device'] ?? '').toString(),
        details: (j['details'] ?? '').toString(),
        status: (j['status'] ?? '').toString(),
      );
}

class ErrorListPage extends StatefulWidget {
  const ErrorListPage({Key? key}) : super(key: key);

  @override
  State<ErrorListPage> createState() => _ErrorListPageState();
}

class _ErrorListPageState extends State<ErrorListPage> {
  static String baseUrl = '${AppLink.server}/Admin/error';
  static const String listEndpoint = "error_list_last20.php";
  static const String searchEndpoint = "error_search_by_phone.php";

  final TextEditingController _phoneCtrl = TextEditingController();
  bool _loading = false;
  String? _errorMsg;
  List<ErrorLog> _items = [];
  bool _searchMode = false;

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

  Future<void> _fetchLast20() async {
    setState(() {
      _loading = true;
      _errorMsg = null;
      _searchMode = false;
    });
    try {
      final res =
          await CRUD().post(link: "$baseUrl/$listEndpoint", payload: {});
      final map = (res);
      if (map['status'] == 'success') {
        final List data = (map['message'] ?? []) as List;
        final items = data.map((e) => ErrorLog.fromJson(e)).toList();
        setState(() {
          _items = items.cast<ErrorLog>();
        });
      } else {
        setState(() => _errorMsg = map['message']?.toString() ?? 'Failed');
      }
    } catch (e) {
      setState(() => _errorMsg = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _searchByPhone() async {
    final phone = _phoneCtrl.text.trim();
    if (phone.isEmpty) {
      return _fetchLast20();
    }
    setState(() {
      _loading = true;
      _errorMsg = null;
      _searchMode = true;
    });
    try {
      final res = await CRUD()
          .post(link: "$baseUrl/$searchEndpoint", payload: {"phone": phone});
      final map = (res);
      if (map['status'] == 'success') {
        final List data = (map['message'] ?? []) as List;
        final items = data.map((e) => ErrorLog.fromJson(e)).toList();
        setState(() {
          _items = items.cast<ErrorLog>();
        });
      } else {
        setState(() => _errorMsg = map['message']?.toString() ?? 'Failed');
      }
    } catch (e) {
      setState(() => _errorMsg = e.toString());
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  void _clearSearch() {
    _phoneCtrl.clear();
    FocusScope.of(context).unfocus();
    _fetchLast20();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: const Text('سجل الأخطاء'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 1.0,
        centerTitle: true,
      ),
      body: Column(
        children: [
          _SearchBar(
            controller: _phoneCtrl,
            onSearch: _searchByPhone,
            onClear: _clearSearch,
          ),
          Expanded(
            child: _buildBody(),
          ),
        ],
      ),
    );
  }

  Widget _buildBody() {
    if (_loading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMsg != null) {
      return Center(
        child: Text(
          _errorMsg!,
          style: TextStyle(color: Colors.red[700]),
        ),
      );
    }

    if (_items.isEmpty) {
      return const Center(child: Text('لا توجد سجلات'));
    }

    return RefreshIndicator(
      onRefresh: () async {
        if (_searchMode) {
          await _searchByPhone();
        } else {
          await _fetchLast20();
        }
      },
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        itemCount: _items.length,
        itemBuilder: (context, index) {
          final e = _items[index];
          return _ErrorTile(e);
        },
      ),
    );
  }
}

class _SearchBar extends StatelessWidget {
  final TextEditingController controller;
  final VoidCallback onSearch;
  final VoidCallback onClear;

  const _SearchBar({
    required this.controller,
    required this.onSearch,
    required this.onClear,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: controller,
                keyboardType: TextInputType.phone,
                onSubmitted: (_) => onSearch(),
                decoration: const InputDecoration(
                  hintText: 'بحث برقم الهاتف...',
                  prefixIcon: Icon(Icons.search),
                  border: InputBorder.none,
                ),
              ),
            ),
            const SizedBox(width: 8),
            ElevatedButton(
              onPressed: onSearch,
              child: const Text('بحث'),
            ),
            const SizedBox(width: 8),
            TextButton(
              onPressed: onClear,
              child: const Text('مسح'),
            ),
          ],
        ),
      ),
    );
  }
}

class _ErrorTile extends StatelessWidget {
  final ErrorLog item;
  const _ErrorTile(this.item);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    // تحديد الألوان بناءً على نوع المستخدم
    Color? typeBgColor;
    Color? typeTextColor;

    final type = item.userType.toLowerCase();
    if (type.contains('driver') || type.contains('سائق')) {
      typeBgColor = Colors.green.shade100;
      typeTextColor = Colors.green.shade800;
    } else if (type.contains('passenger') || type.contains('راكب')) {
      typeBgColor = Colors.amber.shade100; // لون ذهبي/أصفر
      typeTextColor = Colors.amber.shade900;
    }

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // السطر الأول: نص الخطأ (قابل للنسخ)
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: SelectableText(
                    item.error.isEmpty ? '(بدون عنوان)' : item.error,
                    style: theme.textTheme.titleMedium
                        ?.copyWith(fontWeight: FontWeight.bold),
                  ),
                ),
                // تم إزالة _StatusPill (ويدجت الحالة New) من هنا
              ],
            ),
            const SizedBox(height: 8),
            // تفاصيل مختصرة (قابل للنسخ)
            if (item.details.isNotEmpty)
              SelectableText(
                item.details,
                style: theme.textTheme.bodyMedium
                    ?.copyWith(color: Colors.grey[700]),
              ),
            const SizedBox(height: 12),
            // معلومات تقنية
            Wrap(
              spacing: 8,
              runSpacing: 6,
              children: [
                _KV('الهاتف', item.phone),
                _KV('المستخدم', item.userId),
                // تمرير الألوان المخصصة لنوع المستخدم
                _KV(
                  'النوع',
                  item.userType,
                  bgColor: typeBgColor,
                  textColor: typeTextColor,
                ),
                _KV('الجهاز', item.device),
                _KV('التاريخ', item.createdAt),
                _KV('ID', item.id),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class _KV extends StatelessWidget {
  final String k;
  final String v;
  final Color? bgColor;
  final Color? textColor;

  const _KV(this.k, this.v, {this.bgColor, this.textColor});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: bgColor ?? Colors.grey[200],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text.rich(TextSpan(
        style: TextStyle(fontSize: 11, color: textColor ?? Colors.grey[600]),
        children: [
          TextSpan(text: "$k: "),
          TextSpan(
            text: v.isEmpty ? '—' : v,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: textColor ?? Colors.grey[800],
            ),
          ),
        ],
      )),
    );
  }
}
