import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/profile/profile_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/settings_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/profile/profile_screen.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/contact_screen.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/display_mode_setting.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/email_setting.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/language_setting.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/notifications_setting.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/privacy_setting.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/security_setting.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/terms_services_screen.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/settings/widgets/text_size_setting.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  _SettingsScreenState createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  // Get the profile controller to access user data
  final SettingsController _settingController = Get.find<SettingsController>();
  final ProfileController _profileController = Get.find<ProfileController>();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);

    // Fetch user profile data if it's not already loaded
    if (!_profileController.isInitialized.value) {
      _profileController.fetchUserProfile();
    }
  }

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

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

    return Scaffold(
      appBar: AppBar(
        title: Text('Settings', style: theme.textTheme.headlineMedium),
        backgroundColor: theme.scaffoldBackgroundColor,
        elevation: 0,
      ),
      body: Column(
        children: [
          // Profile Section with real data
          Obx(() {
            // Show loading profile if data is being fetched
            if (_profileController.isFetching.value) {
              return Container(
                padding: const EdgeInsets.all(20),
                color: theme.scaffoldBackgroundColor,
                child: Center(
                  child: CircularProgressIndicator(color: theme.primaryColor),
                ),
              );
            }

            // Show error state if there is an error
            if (_profileController.errorMessage.value.isNotEmpty) {
              return Container(
                padding: const EdgeInsets.all(20),
                color: theme.scaffoldBackgroundColor,
                child: Center(
                  child: Text(
                    'Failed to load profile',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: TColors.error,
                    ),
                  ),
                ),
              );
            }

            // Get user data
            final profile = _profileController.profile.value;
            final user = _profileController.user.value;
            final officer = _profileController.officer.value;

            // Get display name and avatar
            final displayName =
                profile?.fullName ?? user?.email.split('@').first ?? 'User';
            final username =
                profile?.username ?? user?.email.split('@').first ?? '';
            final avatarUrl = profile?.avatar ?? officer?.avatar;

            return InkWell(
              onTap: () {
                // Navigate to the ProfileScreen when tapped
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder:
                        (context) => const ProfileScreen(isCurrentUser: true),
                  ),
                );
              },
              child: Container(
                padding: const EdgeInsets.all(20),
                color: theme.scaffoldBackgroundColor,
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 30,
                      backgroundColor: theme.hintColor,
                      backgroundImage:
                          avatarUrl != null ? NetworkImage(avatarUrl) : null,
                      child:
                          avatarUrl == null
                              ? Icon(
                                Icons.person,
                                size: 35,
                                color: theme.scaffoldBackgroundColor,
                              )
                              : null,
                    ),
                    const SizedBox(width: 15),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(displayName, style: theme.textTheme.titleLarge),
                          Text(username, style: theme.textTheme.bodySmall),
                        ],
                      ),
                    ),
                    Icon(Icons.chevron_right, color: theme.hintColor),
                  ],
                ),
              ),
            );
          }),

          // Tab Bar
          Container(
            color: theme.scaffoldBackgroundColor,
            child: TabBar(
              controller: _tabController,
              labelColor: theme.primaryColor,
              unselectedLabelColor: theme.hintColor,
              indicatorColor: theme.primaryColor,
              indicatorWeight: 2,
              labelStyle: theme.textTheme.labelLarge?.copyWith(
                fontWeight: FontWeight.w600,
              ),
              tabs: const [
                Tab(text: 'ACCOUNT'),
                Tab(text: 'SOCIAL'),
                Tab(text: 'DEVICES'),
              ],
            ),
          ),

          // Tab Content
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildAccountTab(),
                _buildSocialTab(),
                _buildDevicesTab(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAccountTab() {
    final theme = Theme.of(context);

    return Container(
      color: theme.scaffoldBackgroundColor,
      padding: const EdgeInsets.symmetric(horizontal: TSizes.defaultSpace / 2),
      child: ListView(
        children: [
          _buildSettingsItem(
            icon: Icons.email_outlined,
            title: 'Email',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const EmailSettingsScreen(),
                ),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.notifications_outlined,
            title: 'Notifications',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const NotificationsSettingsScreen(),
                ),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.lock_outline,
            title: 'Privacy',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const PrivacySettingsScreen(),
                ),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.security_outlined,
            title: 'Security',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const SecuritySettingsScreen(),
                ),
              );
            },
          ),
          const SizedBox(height: 20),
          _buildSettingsItem(
            icon: Icons.dark_mode_outlined,
            title: 'Display mode',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const DisplayModeSettingsScreen(),
                ),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.text_fields_outlined,
            title: 'Text size',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const TextSizeSettingsScreen(),
                ),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.language_outlined,
            title: 'Language',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const LanguageSettingsScreen(),
                ),
              );
            },
          ),
          const SizedBox(height: 20),
          _buildSettingsItem(
            icon: Icons.description_outlined,
            title: 'Terms and services',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const TermsServicesScreen(),
                ),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.help_outline,
            title: 'Contact',
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const ContactScreen()),
              );
            },
          ),
          _buildSettingsItem(
            icon: Icons.logout,
            title: 'Sign Out',
            isDestructive: true,
            onTap: () => _settingController.handleSignOut(context),
          ),

          // Add some padding at the bottom for better scroll experience
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildSocialTab() {
    final theme = Theme.of(context);

    return Container(
      color: theme.scaffoldBackgroundColor,
      child: Center(
        child: Text(
          'Social Settings',
          style: theme.textTheme.titleLarge?.copyWith(color: theme.hintColor),
        ),
      ),
    );
  }

  Widget _buildDevicesTab() {
    final theme = Theme.of(context);

    return Container(
      color: theme.scaffoldBackgroundColor,
      child: Center(
        child: Text(
          'Device Settings',
          style: theme.textTheme.titleLarge?.copyWith(color: theme.hintColor),
        ),
      ),
    );
  }

  Widget _buildSettingsItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
    bool isDestructive = false,
  }) {
    final theme = Theme.of(context);

    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        child: Row(
          children: [
            Icon(
              icon,
              size: 24,
              color: isDestructive ? TColors.error : theme.iconTheme.color,
            ),
            const SizedBox(width: 15),
            Expanded(
              child: Text(
                title,
                style: theme.textTheme.bodyLarge?.copyWith(
                  color: isDestructive ? TColors.error : null,
                ),
              ),
            ),
            Icon(
              Icons.chevron_right,
              color: isDestructive ? TColors.error : theme.hintColor,
            ),
          ],
        ),
      ),
    );
  }
}

