import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/settings_controller.dart';
import '../../../app/routes/app_pages.dart';
import '../../../core/utils/app_snackbar.dart';

class SettingsView extends GetView<SettingsController> {
  const SettingsView({super.key});

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

    return Column(
      children: [
        // Custom Top Bar
        Container(
          padding: EdgeInsets.only(
              top: MediaQuery.of(context).padding.top,
              left: 8,
              right: 8,
              bottom: 12),
          color: isDark ? const Color(0xFF1E1E2E) : const Color(0xFF0F4C81),
          child: const Row(
            children: [
              SizedBox(width: 48),
              Expanded(
                child: Center(
                  child: Text(
                    'الإعدادات',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              SizedBox(width: 48),
            ],
          ),
        ),

        Expanded(
          child: Obx(() => ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  _buildProfileCard(isDark),
                  const SizedBox(height: 24),
                  _buildSectionTitle('المظهر', Icons.palette_rounded, isDark),
                  const SizedBox(height: 8),
                  _buildSettingsCard(isDark, [
                    _buildSwitchTile(
                      icon: Icons.dark_mode_rounded,
                      title: 'الوضع الداكن',
                      subtitle: 'تفعيل المظهر الداكن للتطبيق',
                      value: controller.isDarkMode.value,
                      onChanged: (v) => controller.toggleTheme(),
                      isDark: isDark,
                    ),
                  ]),
                  const SizedBox(height: 20),
                  _buildSectionTitle(
                      'الإشعارات', Icons.notifications_rounded, isDark),
                  const SizedBox(height: 8),
                  _buildSettingsCard(isDark, [
                    _buildSwitchTile(
                      icon: Icons.notifications_active_rounded,
                      title: 'إشعارات الدفع',
                      subtitle: 'استلام إشعارات عند اكتمال المعالجة',
                      value: controller.pushEnabled.value,
                      onChanged: (v) => controller.togglePush(),
                      isDark: isDark,
                    ),
                  ]),
                  const SizedBox(height: 20),

                  // Admin Section
                  Obx(() {
                    if (controller.userRole.value == 'admin' ||
                        controller.userRole.value == 'super_admin') {
                      return Column(
                        children: [
                           _buildSectionTitle('إدارة الأعمال والصلاحيات',
                               Icons.admin_panel_settings_rounded, isDark, 
                               showBackground: true),
                          const SizedBox(height: 8),
                           _buildSettingsCard(isDark, [
                             _buildInfoTile(
                               icon: Icons.business_rounded,
                               title: 'الشركات والموظفين',
                               trailing: 'إدارة →',
                               isDark: isDark,
                               onTap: () {
                                 Get.toNamed(AppRoutes.COMPANIES_MANAGEMENT);
                               },
                             ),
                             if (controller.userRole.value == 'super_admin') ...[
                               const Divider(height: 1),
                               _buildInfoTile(
                                 icon: Icons.account_balance_rounded,
                                 title: 'المكاتب المحاسبية',
                                 trailing: 'إدارة →',
                                 isDark: isDark,
                                 onTap: () {
                                   Get.toNamed(AppRoutes.TENANTS_MANAGEMENT);
                                 },
                               ),
                             ],
                             const Divider(height: 1),
                             _buildInfoTile(
                               icon: Icons.group_rounded,
                               title: 'مستخدمي النظام',
                               trailing: 'إدارة →',
                               isDark: isDark,
                               onTap: () {
                                 Get.toNamed(AppRoutes.USERS_MANAGEMENT);
                               },
                             ),
                           ]),
                          const SizedBox(height: 20),
                        ],
                      );
                    }
                    return const SizedBox.shrink();
                  }),

                  _buildSectionTitle('حول التطبيق', Icons.info_rounded, isDark),
                  const SizedBox(height: 8),
                  _buildSettingsCard(isDark, [
                    _buildInfoTile(
                      icon: Icons.verified_rounded,
                      title: 'الإصدار',
                      trailing: '1.0.0',
                      isDark: isDark,
                    ),
                    const Divider(height: 1),
                    _buildInfoTile(
                      icon: Icons.diamond_rounded,
                      title: 'الاشتراكات والباقات',
                      trailing: 'ترقية →',
                      isDark: isDark,
                      onTap: () => Get.toNamed(AppRoutes.SUBSCRIPTION),
                    ),
                    const Divider(height: 1),
                    _buildInfoTile(
                      icon: Icons.support_agent_rounded,
                      title: 'الدعم الفني',
                      trailing: 'support@musadaq.jo',
                      isDark: isDark,
                    ),
                    const Divider(height: 1),
                    _buildInfoTile(
                      icon: Icons.description_rounded,
                      title: 'سياسة الخصوصية',
                      trailing: '→',
                      isDark: isDark,
                      onTap: () {},
                    ),
                  ]),
                  const SizedBox(height: 32),
                  _buildLogoutButton(),
                  const SizedBox(height: 16),
                  Center(
                    child: TextButton(
                      onPressed: () => _confirmDeleteAccount(context),
                      child: const Text(
                        'حذف الحساب',
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: 13,
                            decoration: TextDecoration.underline),
                      ),
                    ),
                  ),
                  const SizedBox(height: 40),
                ],
              )),
        ),
      ],
    );
  }

  Widget _buildProfileCard(bool isDark) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF0F4C81), Color(0xFF1A6BB5)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Obx(() => Row(
            children: [
              Container(
                width: 56,
                height: 56,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Center(
                  child: Text(
                    (controller.userName.value.isNotEmpty
                            ? controller.userName.value[0]
                            : 'م')
                        .toUpperCase(),
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      controller.userName.value.isNotEmpty
                          ? controller.userName.value
                          : 'مستخدم مُصادَق',
                      style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      controller.userPhone.value,
                      style: TextStyle(
                          color: Colors.white.withOpacity(0.7),
                          fontSize: 13,
                          fontFamily: 'monospace'),
                    ),
                  ],
                ),
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                decoration: BoxDecoration(
                  color: const Color(0xFFD4AF37).withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                      color: const Color(0xFFD4AF37).withOpacity(0.5)),
                ),
                child: Text(
                  controller.roleName,
                  style: const TextStyle(
                      color: Color(0xFFF0D060),
                      fontSize: 11,
                      fontWeight: FontWeight.w600),
                ),
              ),
            ],
          )),
    );
  }

  Widget _buildSectionTitle(String title, IconData icon, bool isDark,
      {bool showBackground = false}) {
    return Container(
      padding: showBackground
          ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8)
          : null,
      decoration: showBackground
          ? BoxDecoration(
              color: const Color(0xFF0F4C81).withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            )
          : null,
      child: Row(
        children: [
          Icon(icon,
              size: 18, color: showBackground ? const Color(0xFF0F4C81) : const Color(0xFF0F4C81)),
          const SizedBox(width: 8),
          Text(title,
              style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w700,
                  color: isDark ? Colors.white70 : const Color(0xFF0F4C81))),
        ],
      ),
    );
  }

  Widget _buildSettingsCard(bool isDark, List<Widget> children) {
    return Container(
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
        borderRadius: BorderRadius.circular(14),
        border:
            Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      child: Column(children: children),
    );
  }

  Widget _buildSwitchTile({
    required IconData icon,
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
    required bool isDark,
  }) {
    return ListTile(
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: const Color(0xFF0F4C81).withOpacity(0.08),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Icon(icon, color: const Color(0xFF0F4C81), size: 20),
      ),
      title: Text(title,
          style: TextStyle(
              fontWeight: FontWeight.w600,
              color: isDark ? Colors.white : Colors.black87)),
      subtitle: Text(subtitle,
          style: TextStyle(
              fontSize: 12, color: isDark ? Colors.white38 : Colors.grey)),
      trailing: Switch.adaptive(
        value: value,
        onChanged: onChanged,
        activeColor: const Color(0xFF0F4C81),
      ),
    );
  }

  Widget _buildInfoTile({
    required IconData icon,
    required String title,
    required String trailing,
    required bool isDark,
    VoidCallback? onTap,
  }) {
    return ListTile(
      onTap: onTap,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: const Color(0xFF0F4C81).withOpacity(0.08),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Icon(icon, color: const Color(0xFF0F4C81), size: 20),
      ),
      title: Text(title,
          style: TextStyle(
              fontWeight: FontWeight.w600,
              color: isDark ? Colors.white : Colors.black87)),
      trailing: Text(trailing,
          style: TextStyle(
              fontSize: 13, color: isDark ? Colors.white38 : Colors.grey)),
    );
  }

  Widget _buildLogoutButton() {
    return SizedBox(
      width: double.infinity,
      height: 52,
      child: ElevatedButton.icon(
        onPressed: () => _confirmLogout(),
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFFFEE2E2),
          foregroundColor: const Color(0xFFDC2626),
          elevation: 0,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
        ),
        icon: const Icon(Icons.logout_rounded),
        label: const Text('تسجيل الخروج',
            style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16)),
      ),
    );
  }

  void _confirmLogout() {
    Get.defaultDialog(
      title: 'تسجيل الخروج',
      middleText: 'هل أنت متأكد من رغبتك في تسجيل الخروج؟',
      textConfirm: 'خروج',
      textCancel: 'إلغاء',
      confirmTextColor: Colors.white,
      buttonColor: const Color(0xFFDC2626),
      onConfirm: () => controller.logout(),
      titleStyle: const TextStyle(fontWeight: FontWeight.bold),
      radius: 14,
    );
  }

  void _confirmDeleteAccount(BuildContext context) {
    Get.defaultDialog(
      title: '⚠️ حذف الحساب',
      middleText:
          'سيتم حذف جميع بياناتك نهائياً. هذا الإجراء لا يمكن التراجع عنه.',
      textConfirm: 'حذف نهائي',
      textCancel: 'إلغاء',
      confirmTextColor: Colors.white,
      buttonColor: const Color(0xFFDC2626),
      onConfirm: () {
        Get.back();
        AppSnackbar.showInfo('قريباً', 'سيتم تفعيل هذه الميزة قريباً');
      },
      titleStyle: const TextStyle(fontWeight: FontWeight.bold),
      radius: 14,
    );
  }
}
