import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/tenants_management_controller.dart';
import 'add_tenant_view.dart';

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

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(TenantsManagementController());
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      backgroundColor: isDark ? const Color(0xFF121212) : const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: const Text('إدارة المكاتب المحاسبية', style: TextStyle(fontWeight: FontWeight.bold)),
        centerTitle: true,
        backgroundColor: const Color(0xFF0F4C81),
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_rounded),
            onPressed: () => controller.fetchTenants(),
          ),
          IconButton(
            icon: const Icon(Icons.add_circle_outline),
            onPressed: () async {
              await Get.to(() => const AddTenantView());
              controller.fetchTenants();
            },
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator(color: Color(0xFF0F4C81)));
        }

        if (controller.tenants.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 80, height: 80,
                  decoration: BoxDecoration(
                    color: const Color(0xFF0F4C81).withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: const Icon(Icons.account_balance, size: 40, color: Color(0xFF0F4C81)),
                ),
                const SizedBox(height: 16),
                Text('لا يوجد مكاتب محاسبية', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: isDark ? Colors.white54 : Colors.grey)),
                const SizedBox(height: 8),
                Text('اضغط + لإضافة مكتب جديد', style: TextStyle(fontSize: 13, color: isDark ? Colors.white24 : Colors.grey.shade400)),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: controller.fetchTenants,
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: controller.tenants.length,
            itemBuilder: (context, index) {
              return _buildTenantCard(controller.tenants[index], controller, isDark, context);
            },
          ),
        );
      }),
    );
  }

  Widget _buildTenantCard(Map<String, dynamic> tenant, TenantsManagementController controller, bool isDark, BuildContext context) {
    final status = tenant['status'] ?? 'active';
    final isActive = status == 'active';
    final companiesCount = tenant['companies_count'] ?? tenant['company_count'] ?? 0;
    final usersCount = tenant['users_count'] ?? tenant['user_count'] ?? 0;

    return Container(
      margin: const EdgeInsets.only(bottom: 14),
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
        boxShadow: [
          if (!isDark) BoxShadow(color: Colors.black.withValues(alpha: 0.04), blurRadius: 8, offset: const Offset(0, 2)),
        ],
      ),
      child: Column(
        children: [
          // Header
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: isActive
                    ? [const Color(0xFF0F4C81).withValues(alpha: 0.08), const Color(0xFF0F4C81).withValues(alpha: 0.02)]
                    : [Colors.red.withValues(alpha: 0.08), Colors.red.withValues(alpha: 0.02)],
                begin: Alignment.topLeft, end: Alignment.bottomRight,
              ),
              borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
            ),
            child: Row(
              children: [
                Container(
                  width: 50, height: 50,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(colors: [Color(0xFF0F4C81), Color(0xFF1A6BB5)]),
                    borderRadius: BorderRadius.circular(14),
                  ),
                  child: const Icon(Icons.account_balance, color: Colors.white, size: 24),
                ),
                const SizedBox(width: 14),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        tenant['name'] ?? 'مكتب محاسبي',
                        style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold, color: isDark ? Colors.white : const Color(0xFF0F172A)),
                      ),
                      const SizedBox(height: 4),
                      if (tenant['email'] != null && tenant['email'].toString().isNotEmpty)
                        Text(tenant['email'], style: TextStyle(fontSize: 13, color: isDark ? Colors.white38 : Colors.grey)),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  decoration: BoxDecoration(
                    color: (isActive ? const Color(0xFF10B981) : Colors.red).withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(isActive ? Icons.check_circle : Icons.block, size: 14, color: isActive ? const Color(0xFF10B981) : Colors.red),
                      const SizedBox(width: 4),
                      Text(isActive ? 'نشط' : 'معطّل', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: isActive ? const Color(0xFF10B981) : Colors.red)),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // Stats row
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              children: [
                _statChip(Icons.business, '$companiesCount شركة', const Color(0xFF3B82F6), isDark),
                const SizedBox(width: 10),
                _statChip(Icons.people, '$usersCount مستخدم', const Color(0xFF6366F1), isDark),
                const SizedBox(width: 10),
                if (tenant['phone'] != null && tenant['phone'].toString().isNotEmpty)
                  _statChip(Icons.phone, tenant['phone'], const Color(0xFF10B981), isDark),
              ],
            ),
          ),

          // Actions
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              border: Border(top: BorderSide(color: isDark ? Colors.white10 : Colors.grey.shade100)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton.icon(
                  onPressed: () => _showEditDialog(context, tenant, controller),
                  icon: const Icon(Icons.edit, size: 16, color: Color(0xFF0F4C81)),
                  label: const Text('تعديل', style: TextStyle(color: Color(0xFF0F4C81), fontSize: 13)),
                ),
                const SizedBox(width: 4),
                TextButton.icon(
                  onPressed: () => _confirmDelete(context, controller, tenant['id'], tenant['name'] ?? ''),
                  icon: const Icon(Icons.delete_outline, size: 16, color: Colors.red),
                  label: const Text('حذف', style: TextStyle(color: Colors.red, fontSize: 13)),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _statChip(IconData icon, String label, Color color, bool isDark) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.08),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: color),
          const SizedBox(width: 4),
          Text(label, style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: color)),
        ],
      ),
    );
  }

  void _showEditDialog(BuildContext context, Map<String, dynamic> tenant, TenantsManagementController controller) {
    final nameC = TextEditingController(text: tenant['name'] ?? '');
    final emailC = TextEditingController(text: tenant['email'] ?? '');
    final phoneC = TextEditingController(text: tenant['phone'] ?? '');
    final addressC = TextEditingController(text: tenant['address'] ?? '');

    Get.dialog(
      AlertDialog(
        title: const Text('تعديل بيانات المكتب', textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold)),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _editField('اسم المكتب', nameC, Icons.account_balance),
              _editField('البريد الإلكتروني', emailC, Icons.email),
              _editField('رقم الهاتف', phoneC, Icons.phone),
              _editField('العنوان', addressC, Icons.location_on),
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('إلغاء')),
          ElevatedButton(
            onPressed: () {
              Get.back();
              controller.updateTenant(tenant['id'], {
                'name': nameC.text,
                'email': emailC.text,
                'phone': phoneC.text,
                'address': addressC.text,
              });
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF0F4C81),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            ),
            child: const Text('حفظ', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
          ),
        ],
      ),
    );
  }

  Widget _editField(String label, TextEditingController controller, IconData icon) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: TextField(
        controller: controller,
        textDirection: TextDirection.rtl,
        decoration: InputDecoration(
          labelText: label,
          prefixIcon: Icon(icon, size: 20),
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, TenantsManagementController controller, String id, String name) {
    Get.defaultDialog(
      title: 'حذف المكتب المحاسبي',
      middleText: 'هل أنت متأكد من حذف "$name"؟\nسيتم حذف جميع بياناته.',
      textConfirm: 'حذف نهائي',
      textCancel: 'إلغاء',
      confirmTextColor: Colors.white,
      buttonColor: Colors.red,
      onConfirm: () {
        Get.back();
        controller.deleteTenant(id);
      },
    );
  }
}
