import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/profile/presentation/providers/profile_provider.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/profile_settings_tab.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/change_password_tab.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/notifications_tab.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/privacy_tab.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/billing_tab.dart';
import 'package:real_estate_mobile/features/profile/presentation/widgets/testimonials_tab.dart';

class ProfileSettingsScreen extends ConsumerStatefulWidget {
  const ProfileSettingsScreen({super.key});

  @override
  ConsumerState<ProfileSettingsScreen> createState() =>
      _ProfileSettingsScreenState();
}

class _ProfileSettingsScreenState extends ConsumerState<ProfileSettingsScreen> {
  int _selectedTab = 0;

  List<_TabItem> _getTabs(bool isAgent) {
    final tabs = <_TabItem>[
      _TabItem(label: 'Profile Settings', icon: Icons.person_outline),
      _TabItem(label: 'Change Password', icon: Icons.lock_outline),
      _TabItem(label: 'Notifications', icon: Icons.notifications_none),
      _TabItem(label: 'Privacy', icon: Icons.shield_outlined),
    ];
    if (isAgent) {
      tabs.add(
          _TabItem(label: 'Billings & Payments', icon: Icons.payment_outlined));
      tabs.add(
          _TabItem(label: 'Add Testimonials', icon: Icons.rate_review_outlined));
    }
    return tabs;
  }

  @override
  Widget build(BuildContext context) {
    final profileState = ref.watch(profileProvider);

    ref.listen<ProfileState>(profileProvider, (prev, next) {
      if (next.successMessage != null && prev?.successMessage == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(next.successMessage!),
            backgroundColor: const Color(0xFF638559),
          ),
        );
      }
      if (next.errorMessage != null && prev?.errorMessage == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(next.errorMessage!),
            backgroundColor: Colors.red,
          ),
        );
      }
    });

    if (profileState.isLoading) {
      return const Center(
        child: CircularProgressIndicator(color: AppColors.accentOrange),
      );
    }

    final tabs = _getTabs(profileState.isAgent);
    final totalTabs = tabs.length;

    return Column(
      children: [
        const SizedBox(height: 16),
        _buildTabBar(tabs),
        _buildProgressBar(totalTabs),
        Expanded(child: _buildSelectedTab(tabs)),
      ],
    );
  }

  Widget _buildSelectedTab(List<_TabItem> tabs) {
    final label = tabs[_selectedTab].label;
    switch (label) {
      case 'Profile Settings':
        return const ProfileSettingsTab();
      case 'Change Password':
        return const ChangePasswordTab();
      case 'Notifications':
        return const NotificationsTab();
      case 'Privacy':
        return const PrivacyTab();
      case 'Billings & Payments':
        return const BillingTab();
      case 'Add Testimonials':
        return const TestimonialsTab();
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildTabBar(List<_TabItem> tabs) {
    return SizedBox(
      height: 46,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 7),
        itemCount: tabs.length,
        separatorBuilder: (_, __) => const SizedBox(width: 6),
        itemBuilder: (_, i) => _buildTab(i, tabs[i]),
      ),
    );
  }

  Widget _buildTab(int index, _TabItem tab) {
    final isActive = _selectedTab == index;
    return GestureDetector(
      onTap: () => setState(() => _selectedTab = index),
      child: Container(
        width: 162,
        height: 46,
        decoration: BoxDecoration(
          color: isActive ? AppColors.accentOrange : Colors.transparent,
          borderRadius: BorderRadius.circular(15),
          border: Border.all(
            color: isActive
                ? AppColors.accentOrange
                : AppColors.primaryDark.withValues(alpha: 0.2),
            width: 0.1,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(tab.icon,
                size: 20,
                color: isActive ? Colors.white : AppColors.primaryDark),
            const SizedBox(width: 8),
            Flexible(
              child: Text(
                tab.label,
                style: TextStyle(
                  fontFamily: 'SourceSerif4',
                  fontSize: 13,
                  fontWeight: FontWeight.w400,
                  color: isActive ? Colors.white : AppColors.primaryDark,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressBar(int totalTabs) {
    final progress = (_selectedTab + 1) / totalTabs;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 16),
      child: Container(
        height: 5,
        decoration: BoxDecoration(
          color: const Color(0xFFD9D9D9),
          borderRadius: BorderRadius.circular(15),
        ),
        child: Align(
          alignment: Alignment.centerLeft,
          child: FractionallySizedBox(
            widthFactor: progress,
            child: Container(
              decoration: BoxDecoration(
                color: AppColors.primaryDark.withValues(alpha: 0.75),
                borderRadius: BorderRadius.circular(15),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _TabItem {
  final String label;
  final IconData icon;
  const _TabItem({required this.label, required this.icon});
}
