import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/employee_controller/employee_controller.dart';
import 'package:sefer_admin1/controller/functions/upload_image copy.dart'; // تأكد من مسار الملف الصحيح
import 'package:url_launcher/url_launcher.dart';

class EmployeePage extends StatelessWidget {
  const EmployeePage({super.key});

  @override
  Widget build(BuildContext context) {
    // حقن الكنترولر
    Get.put(EmployeeController());

    // ألوان الثيم
    const Color bgColor = Color(0xFF0A0E27);
    const Color cardColor = Color(0xFF1A1F3A);
    const Color primaryAccent = Color(0xFF6366F1);

    return Scaffold(
      backgroundColor: bgColor,
      body: GetBuilder<EmployeeController>(
        builder: (controller) {
          return CustomScrollView(
            physics: const BouncingScrollPhysics(),
            slivers: [
              // 1. App Bar
              SliverAppBar(
                expandedHeight: 100,
                floating: true,
                pinned: true,
                backgroundColor: bgColor,
                elevation: 0,
                flexibleSpace: FlexibleSpaceBar(
                  titlePadding: const EdgeInsets.only(bottom: 16),
                  title: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: primaryAccent.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: const Icon(Icons.badge_rounded,
                            color: Colors.white, size: 18),
                      ),
                      const SizedBox(width: 10),
                      const Text(
                        'الموظفون',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: Colors.white,
                          fontFamily: 'Segoe UI',
                        ),
                      ),
                    ],
                  ),
                  centerTitle: true,
                  background: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          primaryAccent.withOpacity(0.15),
                          bgColor,
                        ],
                      ),
                    ),
                  ),
                ),
              ),

              // 2. قائمة الموظفين
              if (controller.employee.isEmpty)
                const SliverFillRemaining(
                  child: Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.people_outline,
                            size: 60, color: Colors.white24),
                        SizedBox(height: 16),
                        Text("لا يوجد موظفين حالياً",
                            style: TextStyle(color: Colors.white54)),
                      ],
                    ),
                  ),
                )
              else
                SliverPadding(
                  padding: const EdgeInsets.all(16),
                  sliver: SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        final employee = controller.employee[index];
                        return _EmployeeCard(
                          employee: employee,
                          index: index,
                          cardColor: cardColor,
                          primaryAccent: primaryAccent,
                        );
                      },
                      childCount: controller.employee.length,
                    ),
                  ),
                ),
            ],
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          final controller = Get.find<EmployeeController>();
          controller.id = controller.generateRandomId(8);
          Get.to(() => _EmployeeFormScreen(controller: controller));
        },
        backgroundColor: primaryAccent,
        child: const Icon(Icons.person_add_rounded, color: Colors.white),
      ),
    );
  }
}

// === بطاقة الموظف (تصميم جديد ومحسن) ===
class _EmployeeCard extends StatelessWidget {
  final Map<String, dynamic> employee;
  final int index;
  final Color cardColor;
  final Color primaryAccent;

  const _EmployeeCard({
    required this.employee,
    required this.index,
    required this.cardColor,
    required this.primaryAccent,
  });

  @override
  Widget build(BuildContext context) {
    bool isExcellent = employee['status'].toString().contains('ممتاز');
    Color statusColor = isExcellent ? const Color(0xFF10B981) : Colors.amber;

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: cardColor,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.white.withOpacity(0.05)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => Get.to(() => EmployeeDetails(index: index)),
          borderRadius: BorderRadius.circular(16),
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // الصف العلوي: الحالة + أيقونة
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.05),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(Icons.person,
                          color: Colors.white.withOpacity(0.7), size: 20),
                    ),
                    Flexible(
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 10, vertical: 6),
                        decoration: BoxDecoration(
                          color: statusColor.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(8),
                          border:
                              Border.all(color: statusColor.withOpacity(0.3)),
                        ),
                        child: Text(
                          employee['status'] ?? 'Unknown',
                          style: TextStyle(
                            color: statusColor,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            height: 1.5,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 12),

                // الاسم في سطر كامل ومميز
                Text(
                  employee['name'] ?? 'Unknown',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    height: 1.3,
                  ),
                ),

                const Padding(
                  padding: EdgeInsets.symmetric(vertical: 12),
                  child: Divider(height: 1, color: Colors.white10),
                ),

                // تفاصيل التعليم والهاتف والموقع (مع دعم تعدد الأسطر)
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _buildInfoRow(Icons.phone_iphone_rounded,
                              employee['phone'] ?? '', Colors.white54),
                          const SizedBox(height: 12), // مسافة أكبر بين العناصر
                          _buildInfoRow(
                              Icons.school_outlined,
                              employee['education'] ?? 'غير محدد',
                              primaryAccent),
                          const SizedBox(height: 12), // مسافة أكبر
                          _buildInfoRow(Icons.location_on_outlined,
                              employee['site'] ?? 'غير محدد', Colors.blueGrey),
                        ],
                      ),
                    ),

                    // زر الاتصال الجانبي
                    const SizedBox(width: 16),
                    Material(
                      color: Colors.green.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                      child: InkWell(
                        onTap: () =>
                            _makePhoneCall(employee['phone'].toString()),
                        borderRadius: BorderRadius.circular(12),
                        child: Container(
                          padding: const EdgeInsets.all(14),
                          child: const Icon(Icons.call,
                              color: Colors.green, size: 24),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String text, Color iconColor) {
    return Row(
      crossAxisAlignment:
          CrossAxisAlignment.start, // محاذاة الأيقونة مع بداية النص
      children: [
        Padding(
          padding: const EdgeInsets.only(top: 2), // ضبط بسيط لموقع الأيقونة
          child: Icon(icon, size: 16, color: iconColor.withOpacity(0.8)),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              color: Colors.white.withOpacity(0.7),
              fontSize: 13,
              height: 1.5, // تباعد الأسطر لسهولة القراءة
            ),
            // تم إزالة maxLines و overflow للسماح بالنص بالنزول لأسطر متعددة
          ),
        ),
      ],
    );
  }

  Future<void> _makePhoneCall(String phoneNumber) async {
    final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber);
    if (await canLaunchUrl(launchUri)) {
      await launchUrl(launchUri);
    }
  }
}

// === شاشة إضافة موظف ===
class _EmployeeFormScreen extends StatelessWidget {
  final EmployeeController controller;
  const _EmployeeFormScreen({required this.controller});

  @override
  Widget build(BuildContext context) {
    const Color bgColor = Color(0xFF0A0E27);
    const Color inputColor = Color(0xFF1A1F3A);

    return Scaffold(
      backgroundColor: bgColor,
      appBar: AppBar(
        title: const Text("إضافة موظف جديد",
            style: TextStyle(color: Colors.white)),
        backgroundColor: bgColor,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Get.back(),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: controller.formKey,
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: _UploadButton(
                      title: "الهوية (أمام)",
                      icon: Icons.credit_card,
                      onPressed: () async {
                        await ImageController().choosImage(AppLink.uploadEgypt,
                            'idFrontEmployee', controller.id);
                      },
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _UploadButton(
                      title: "الهوية (خلف)",
                      icon: Icons.credit_card_outlined,
                      onPressed: () async {
                        await ImageController().choosImage(AppLink.uploadEgypt,
                            'idbackEmployee', controller.id);
                      },
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              _buildModernTextField(
                  controller.name, "الاسم الكامل", Icons.person, inputColor),
              const SizedBox(height: 16),
              _buildModernTextField(
                  controller.phone, "رقم الهاتف", Icons.phone, inputColor,
                  type: TextInputType.phone),
              const SizedBox(height: 16),
              _buildModernTextField(controller.education, "التعليم / الملاحظات",
                  Icons.school, inputColor),
              const SizedBox(height: 16),
              _buildModernTextField(controller.site, "الموقع / العنوان",
                  Icons.location_on, inputColor),
              const SizedBox(height: 16),
              _buildModernTextField(controller.status, "الحالة (مثال: ممتاز)",
                  Icons.star, inputColor),
              const SizedBox(height: 32),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () async {
                    if (controller.formKey.currentState!.validate()) {
                      await controller.addEmployee();
                      Get.back();
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF6366F1),
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                  ),
                  child: const Text("حفظ البيانات",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildModernTextField(TextEditingController controller, String hint,
      IconData icon, Color fillColor,
      {TextInputType type = TextInputType.text}) {
    return Container(
      decoration: BoxDecoration(
        color: fillColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.white.withOpacity(0.1)),
      ),
      child: TextFormField(
        controller: controller,
        keyboardType: type,
        style: const TextStyle(color: Colors.white),
        maxLines: null, // السماح بتعدد الأسطر عند الإدخال أيضاً
        decoration: InputDecoration(
          labelText: hint,
          labelStyle: TextStyle(color: Colors.white.withOpacity(0.5)),
          prefixIcon: Icon(icon, color: Colors.white38, size: 20),
          border: InputBorder.none,
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        ),
        validator: (value) =>
            value == null || value.isEmpty ? 'حقل مطلوب' : null,
      ),
    );
  }
}

class _UploadButton extends StatelessWidget {
  final String title;
  final IconData icon;
  final VoidCallback onPressed;

  const _UploadButton(
      {required this.title, required this.icon, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 20),
        decoration: BoxDecoration(
          color: const Color(0xFF1A1F3A),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
              color: const Color(0xFF6366F1).withOpacity(0.3),
              style: BorderStyle.solid),
        ),
        child: Column(
          children: [
            Icon(icon, color: const Color(0xFF6366F1), size: 30),
            const SizedBox(height: 8),
            Text(title,
                style: const TextStyle(color: Colors.white70, fontSize: 12)),
            const SizedBox(height: 4),
            const Text("اضغط للرفع",
                style: TextStyle(color: Colors.white38, fontSize: 10)),
          ],
        ),
      ),
    );
  }
}

// === شاشة التفاصيل ===
class EmployeeDetails extends StatelessWidget {
  final int index;
  const EmployeeDetails({super.key, required this.index});

  @override
  Widget build(BuildContext context) {
    const Color bgColor = Color(0xFF0A0E27);

    return Scaffold(
      backgroundColor: bgColor,
      appBar: AppBar(
        title:
            const Text('تفاصيل الموظف', style: TextStyle(color: Colors.white)),
        backgroundColor: bgColor,
        iconTheme: const IconThemeData(color: Colors.white),
        elevation: 0,
      ),
      body: GetBuilder<EmployeeController>(
        builder: (controller) {
          final employeeId = controller.employee[index]['id'];
          return SingleChildScrollView(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text("الهوية الأمامية",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.bold)),
                const SizedBox(height: 10),
                _buildImageViewer(
                  '${AppLink.server}/card_image/idFrontEmployee-$employeeId.jpg',
                ),
                const SizedBox(height: 30),
                const Text("الهوية الخلفية",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.bold)),
                const SizedBox(height: 10),
                _buildImageViewer(
                  '${AppLink.server}/card_image/idbackEmployee-$employeeId.jpg',
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildImageViewer(String url) {
    return Container(
      width: double.infinity,
      height: 220,
      decoration: BoxDecoration(
        color: const Color(0xFF1A1F3A),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.white.withOpacity(0.1)),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16),
        child: Image.network(
          url,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return const Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.broken_image_rounded,
                      color: Colors.white24, size: 50),
                  SizedBox(height: 8),
                  Text("فشل تحميل الصورة",
                      style: TextStyle(color: Colors.white24)),
                ],
              ),
            );
          },
          loadingBuilder: (context, child, loadingProgress) {
            if (loadingProgress == null) return child;
            return const Center(
                child: CircularProgressIndicator(color: Color(0xFF6366F1)));
          },
        ),
      ),
    );
  }
}
