import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:gap/gap.dart';
import '../../ui/theme/app_theme.dart';
import '../../ui/widgets/structure_widgets.dart';
import '../../ui/widgets/action_widgets.dart';
import '../../state/onboarding_controller.dart';
import 'onboarding_data.dart';
import '../../models/preferences.dart';
import '../../services/auth_service.dart';
import '../../services/firestore_service.dart';

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

  @override
  ConsumerState<OnboardingFlow> createState() => _OnboardingFlowState();
}

class _OnboardingFlowState extends ConsumerState<OnboardingFlow> {
  final PageController _pageController = PageController();
  int _currentPage = 0;
  final int _totalPages = 7;
  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    // Initialize controller with current user ID if available
    final user = ref.read(authServiceProvider).currentUser;
    if (user != null) {
      Future.microtask(
        () => ref.read(onboardingControllerProvider.notifier).init(user.uid),
      );
    }
  }

  void _nextPage() {
    if (_currentPage < _totalPages - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    } else {
      _finish();
    }
  }

  void _finish() async {
    setState(() => _isSaving = true);
    try {
      final user = ref.read(authServiceProvider).currentUser;
      if (user != null) {
        final profile = ref.read(onboardingControllerProvider);
        final boundaries = ref.read(onboardingBoundariesProvider);

        final firestore = ref.read(firestoreServiceProvider);

        // Save Profile
        await firestore.saveUserProfile(
          profile.copyWith(onboardingComplete: true),
        );

        // Save Preferences
        await firestore.savePreferences(
          AppPreferences(
            boundaries: boundaries,
            gentleNudges: true,
            focusProtection: false,
          ),
        );
      }
    } catch (e) {
      print("Error saving onboarding: $e");
    } finally {
      if (mounted) setState(() => _isSaving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AyuelScaffold(
      body: Column(
        children: [
          // Header / Progress
          if (_currentPage > 0)
            Padding(
              padding: const EdgeInsets.all(24.0),
              child: DotsIndicator(
                dotsCount:
                    _totalPages -
                    1, // Exclude welcome page from dots count usually, or include all except welcome
                position: (_currentPage - 1)
                    .clamp(0, _totalPages - 2)
                    .toDouble(),
                decorator: DotsDecorator(
                  activeColor: AppTheme.primary,
                  color: AppTheme.primary.withOpacity(0.2),
                  size: const Size.square(8.0),
                  activeSize: const Size(24.0, 8.0),
                  activeShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                ),
              ),
            ),

          Expanded(
            child: PageView(
              controller: _pageController,
              physics:
                  const NeverScrollableScrollPhysics(), // Force use of buttons
              onPageChanged: (page) => setState(() => _currentPage = page),
              children: [
                _WelcomePage(onNext: _nextPage),
                _PersonaPage(onNext: _nextPage),
                _EnergyPage(onNext: _nextPage),
                _FocusPage(onNext: _nextPage),
                _DecisionStylePage(onNext: _nextPage),
                _BoundariesPage(onNext: _nextPage),
                _FinishPage(onNext: _finish),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 1. Welcome Screen
class _WelcomePage extends StatelessWidget {
  final VoidCallback onNext;
  const _WelcomePage({required this.onNext});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Spacer(),
          // Mascot Icon Placeholder
          Container(
            width: 120,
            height: 120,
            decoration: const BoxDecoration(
              color: AppTheme.surface,
              shape: BoxShape.circle,
            ),
            child: const Center(
              child: Text("🧔", style: TextStyle(fontSize: 60)),
            ),
          ),
          const Gap(40),
          Text(
            "Help with\neveryday decisions",
            style: AppTheme.textTheme.displayLarge,
            textAlign: TextAlign.center,
          ),
          const Gap(16),
          Text(
            "Ayuel helps you make small decisions so you can save energy for the big ones.",
            style: AppTheme.textTheme.bodyLarge,
            textAlign: TextAlign.center,
          ),
          const Spacer(),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(text: "Get a Started", onPressed: onNext),
          ),
          const Gap(20),
        ],
      ),
    );
  }
}

// 2. Persona Selection
class _PersonaPage extends ConsumerWidget {
  final VoidCallback onNext;
  const _PersonaPage({required this.onNext});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedPersona = ref.watch(onboardingControllerProvider).persona;

    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Which sounds most like you?",
            style: AppTheme.textTheme.displayMedium,
          ),
          const Gap(24),
          Expanded(
            child: GridView.count(
              crossAxisCount: 2,
              crossAxisSpacing: 16,
              mainAxisSpacing: 16,
              childAspectRatio: 0.8,
              children: OnboardingData.personas.map((persona) {
                final isSelected = selectedPersona == persona['id'];
                return AyuelCard(
                  selected: isSelected,
                  onTap: () => ref
                      .read(onboardingControllerProvider.notifier)
                      .setPersona(persona['id'] as String),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        persona['icon'] as String,
                        style: const TextStyle(fontSize: 40),
                      ),
                      const Gap(16),
                      Text(
                        persona['title'] as String,
                        style: AppTheme.textTheme.bodyLarge?.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const Gap(8),
                      Text(
                        persona['subtitle'] as String,
                        style: AppTheme.textTheme.bodyMedium?.copyWith(
                          fontSize: 12,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
          ),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(
              text: "Continue",
              onPressed: selectedPersona != null ? onNext : null,
            ),
          ),
        ],
      ),
    );
  }
}

// 3. Energy Baseline
class _EnergyPage extends ConsumerWidget {
  final VoidCallback onNext;
  const _EnergyPage({required this.onNext});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedEnergy = ref
        .watch(onboardingControllerProvider)
        .energyBaseline;

    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "What's your usual energy level?",
            style: AppTheme.textTheme.displayMedium,
          ),
          const Gap(24),
          ...["High Energy", "Variable", "Low Energy", "Reserved"].map(
            (e) => Padding(
              padding: const EdgeInsets.only(bottom: 12.0),
              child: AyuelCard(
                padding: const EdgeInsets.all(16),
                selected: selectedEnergy == e,
                onTap: () => ref
                    .read(onboardingControllerProvider.notifier)
                    .setEnergyBaseline(e),
                child: Row(
                  children: [
                    Radio(
                      value: e,
                      groupValue: selectedEnergy,
                      onChanged: (val) => ref
                          .read(onboardingControllerProvider.notifier)
                          .setEnergyBaseline(val.toString()),
                      activeColor: AppTheme.primary,
                    ),
                    Text(e, style: AppTheme.textTheme.bodyLarge),
                  ],
                ),
              ),
            ),
          ),
          const Spacer(),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(
              text: "Continue",
              onPressed: selectedEnergy != null ? onNext : null,
            ),
          ),
        ],
      ),
    );
  }
}

// 4. Focus Areas
class _FocusPage extends ConsumerWidget {
  final VoidCallback onNext;
  const _FocusPage({required this.onNext});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selected = ref.watch(onboardingControllerProvider).focusAreas;

    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Pick top 3 focus areas",
            style: AppTheme.textTheme.displayMedium,
          ),
          const Gap(24),
          Expanded(
            child: ListView(
              children: OnboardingData.focusAreas.map((area) {
                final isSelected = selected.contains(area);
                return Padding(
                  padding: const EdgeInsets.only(bottom: 12.0),
                  child: AyuelCard(
                    padding: const EdgeInsets.all(16),
                    selected: isSelected,
                    onTap: () => ref
                        .read(onboardingControllerProvider.notifier)
                        .toggleFocusArea(area),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(area, style: AppTheme.textTheme.bodyLarge),
                        if (isSelected)
                          const Icon(
                            Icons.check_circle,
                            color: AppTheme.primary,
                          )
                        else
                          Icon(
                            Icons.circle_outlined,
                            color: AppTheme.textSecondary.withOpacity(0.5),
                          ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(
              text: "Continue",
              onPressed: selected.isNotEmpty ? onNext : null,
            ),
          ),
        ],
      ),
    );
  }
}

// 5. Decision Style
class _DecisionStylePage extends ConsumerWidget {
  final VoidCallback onNext;
  const _DecisionStylePage({required this.onNext});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedStyle = ref.watch(onboardingControllerProvider).decisionStyle;

    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "How should Ayuel help?",
            style: AppTheme.textTheme.displayMedium,
          ),
          const Gap(24),
          ...OnboardingData.decisionStyles.map(
            (style) => Padding(
              padding: const EdgeInsets.only(bottom: 12.0),
              child: AyuelCard(
                selected: selectedStyle == style['id'],
                onTap: () => ref
                    .read(onboardingControllerProvider.notifier)
                    .setDecisionStyle(style['id'] as String),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      style['title'] as String,
                      style: AppTheme.textTheme.bodyLarge?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Text(
                      style['subtitle'] as String,
                      style: AppTheme.textTheme.bodyMedium,
                    ),
                  ],
                ),
              ),
            ),
          ),
          const Spacer(),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(
              text: "Continue",
              onPressed: selectedStyle != null ? onNext : null,
            ),
          ),
        ],
      ),
    );
  }
}

// 6. Boundaries
class _BoundariesPage extends ConsumerWidget {
  final VoidCallback onNext;
  const _BoundariesPage({required this.onNext});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final boundaries = ref.watch(onboardingBoundariesProvider);

    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("Set some boundaries", style: AppTheme.textTheme.displayMedium),
          const Gap(16),
          Text(
            "Ayuel can gently remind you to take breaks or stop for the day.",
            style: AppTheme.textTheme.bodyLarge,
          ),
          const Gap(32),
          Expanded(
            child: ListView(
              children: boundaries.keys.map((key) {
                return SwitchListTile(
                  title: Text(key),
                  value: boundaries[key] ?? false,
                  onChanged: (val) {
                    final newMap = Map<String, bool>.from(boundaries);
                    newMap[key] = val;
                    ref.read(onboardingBoundariesProvider.notifier).set(newMap);
                  },
                  activeColor: AppTheme.primary,
                );
              }).toList(),
            ),
          ),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(text: "Continue", onPressed: onNext),
          ),
        ],
      ),
    );
  }
}

// 7. Finish
class _FinishPage extends StatelessWidget {
  final VoidCallback onNext;
  const _FinishPage({required this.onNext});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Spacer(),
          Container(
            width: 100,
            height: 100,
            decoration: const BoxDecoration(
              color: AppTheme.primary,
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.check, size: 50, color: Colors.white),
          ),
          const Gap(40),
          Text(
            "All set!",
            style: AppTheme.textTheme.displayLarge,
            textAlign: TextAlign.center,
          ),
          const Gap(16),
          Text(
            "You can change anything anytime in settings.",
            style: AppTheme.textTheme.bodyLarge,
            textAlign: TextAlign.center,
          ),
          const Spacer(),
          SizedBox(
            width: double.infinity,
            child: AyuelPrimaryButton(text: "Start my day", onPressed: onNext),
          ),
          const Gap(20),
        ],
      ),
    );
  }
}
