import 'package:flutter/material.dart';
import 'package:siro_admin/constant/colors.dart';
import 'package:siro_admin/constant/links.dart';
import 'package:siro_admin/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: const Color(0xFFF0F4F8),
      appBar: _buildAppBar(),
      body: Column(
        children: [
          _SearchBar(
            controller: _phoneCtrl,
            onSearch: _searchByPhone,
            onClear: _clearSearch,
          ),
          Expanded(
            child: _buildBody(),
          ),
        ],
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      elevation: 0,
      backgroundColor: const Color(0xFF0F172A),
      foregroundColor: Colors.white,
      centerTitle: true,
      title: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.white.withOpacity(0.2)),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 22),
            const SizedBox(width: 8),
            const Text(
              "سجل الأخطاء",
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBody() {
    if (_loading) {
      return const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF0F172A)),
        ),
      );
    }

    if (_errorMsg != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red.shade300),
            const SizedBox(height: 16),
            Text(
              _errorMsg!,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.red.shade700,
                fontSize: 14,
              ),
            ),
          ],
        ),
      );
    }

    if (_items.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.check_circle_outline,
              size: 64,
              color: Colors.green.shade300,
            ),
            const SizedBox(height: 16),
            const Text(
              'لا توجد سجلات أخطاء',
              style: TextStyle(fontSize: 16, color: Colors.grey),
            ),
          ],
        ),
      );
    }

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

  @override
  void dispose() {
    _phoneCtrl.dispose();
    super.dispose();
  }
}

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

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

  @override
  State<_SearchBar> createState() => _SearchBarState();
}

class _SearchBarState extends State<_SearchBar> {
  bool _isFocused = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.white, Colors.grey.shade50],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16,
            spreadRadius: 2,
          )
        ],
      ),
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Focus(
                  onFocusChange: (focused) {
                    setState(() => _isFocused = focused);
                  },
                  child: TextField(
                    controller: widget.controller,
                    keyboardType: TextInputType.phone,
                    textDirection: TextDirection.rtl,
                    onSubmitted: (_) => widget.onSearch(),
                    style: const TextStyle(fontSize: 15),
                    decoration: InputDecoration(
                      hintText: 'بحث برقم الهاتف',
                      hintStyle: TextStyle(color: Colors.grey.shade400),
                      prefixIcon: Icon(
                        Icons.search,
                        color: _isFocused
                            ? const Color(0xFF0F172A)
                            : Colors.grey.shade400,
                      ),
                      suffixIcon: widget.controller.text.isNotEmpty
                          ? InkWell(
                              onTap: () {
                                widget.controller.clear();
                                setState(() {});
                              },
                              child: Icon(Icons.close,
                                  color: Colors.grey.shade400, size: 20),
                            )
                          : null,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide:
                            BorderSide(color: Colors.grey.shade300, width: 1),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide:
                            BorderSide(color: Colors.grey.shade300, width: 1),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: const BorderSide(
                          color: Color(0xFF0F172A),
                          width: 2,
                        ),
                      ),
                      filled: true,
                      fillColor: Colors.white,
                      contentPadding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    onChanged: (_) => setState(() {}),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: widget.onSearch,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF0F172A),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
                child: const Row(
                  children: [
                    Icon(Icons.search, size: 18),
                    SizedBox(width: 6),
                    Text("بحث"),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              OutlinedButton(
                onPressed: widget.onClear,
                style: OutlinedButton.styleFrom(
                  foregroundColor: const Color(0xFF0F172A),
                  side: const BorderSide(
                    color: Color(0xFF0F172A),
                    width: 1.5,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                ),
                child: const Icon(Icons.refresh, size: 20),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _ErrorTile extends StatelessWidget {
  final ErrorLog item;
  final int index;

  const _ErrorTile(this.item, this.index);

  @override
  Widget build(BuildContext context) {
    // تحديد الألوان والأيقونات بناءً على نوع المستخدم
    final isDriver = item.userType.toLowerCase().contains('driver') ||
        item.userType.toLowerCase().contains('سائق');

    final userTypeColor =
        isDriver ? const Color(0xFF10B981) : const Color(0xFFF59E0B);
    final userTypeIcon = isDriver ? Icons.directions_car : Icons.person;
    final userTypeLabel = isDriver ? "سائق" : "راكب";

    final userTypeBgColor = isDriver
        ? const Color(0xFF10B981).withOpacity(0.1)
        : const Color(0xFFF59E0B).withOpacity(0.1);

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.white, Colors.grey.shade50],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.grey.shade200, width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.06),
            blurRadius: 12,
            spreadRadius: 1,
          )
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16),
        child: Stack(
          children: [
            // خط علوي ملون
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 4,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      const Color(0xFFEF4444),
                      Colors.red.shade400,
                    ],
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  // الصف الأول: رقم الخطأ ونوع المستخدم
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: userTypeBgColor,
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: userTypeColor, width: 1),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(userTypeIcon, size: 14, color: userTypeColor),
                            const SizedBox(width: 4),
                            Text(
                              userTypeLabel,
                              style: TextStyle(
                                fontSize: 11,
                                fontWeight: FontWeight.bold,
                                color: userTypeColor,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Text(
                        '#${item.id}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade500,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),

                  // عنوان الخطأ (قابل للنسخ)
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.red.shade50,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: Colors.red.shade200,
                        width: 1,
                      ),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(Icons.warning_amber_rounded,
                            size: 18, color: Colors.red.shade600),
                        const SizedBox(width: 8),
                        Expanded(
                          child: SelectableText(
                            item.error.isEmpty ? '(بدون عنوان)' : item.error,
                            style: TextStyle(
                              fontSize: 13,
                              fontWeight: FontWeight.bold,
                              color: Colors.red.shade900,
                              height: 1.4,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 12),

                  // التفاصيل (إن وجدت)
                  if (item.details.isNotEmpty) ...[
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade50,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(
                          color: Colors.grey.shade200,
                          width: 1,
                        ),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Icon(Icons.info_outline,
                              size: 16, color: Colors.grey.shade600),
                          const SizedBox(width: 8),
                          Expanded(
                            child: SelectableText(
                              item.details,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey.shade700,
                                height: 1.4,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 12),
                  ],

                  // معلومات تقنية
                  Wrap(
                    spacing: 6,
                    runSpacing: 6,
                    alignment: WrapAlignment.end,
                    children: [
                      _buildInfoBadge(
                        icon: Icons.phone,
                        label: 'الهاتف',
                        value: item.phone,
                        color: Colors.blue,
                      ),
                      _buildInfoBadge(
                        icon: Icons.person_outline,
                        label: 'المعرف',
                        value: item.userId,
                        color: Colors.purple,
                      ),
                      _buildInfoBadge(
                        icon: Icons.devices,
                        label: 'Path',
                        value: item.device,
                        color: Colors.orange,
                      ),
                      _buildInfoBadge(
                        icon: Icons.schedule,
                        label: 'التاريخ',
                        value: item.createdAt,
                        color: Colors.teal,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoBadge({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: color.withOpacity(0.08),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withOpacity(0.3), width: 1),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 13, color: color),
          const SizedBox(width: 4),
          Flexible(
            child: Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: "$label: ",
                    style: TextStyle(
                      fontSize: 10,
                      color: color.withOpacity(0.7),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  TextSpan(
                    text: value.isEmpty ? '—' : value,
                    style: TextStyle(
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                      color: color,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
