import 'dart:math' as math;
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../widgets/gradient_mesh.dart';
import '../../widgets/particles.dart';
import '../../widgets/orbit_rings.dart';

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

  @override
  State<OnboardingScreen> createState() => _OnboardingScreenState();
}

class _OnboardingScreenState extends State<OnboardingScreen>
    with TickerProviderStateMixin {
  final _controller = PageController();
  int _page = 0;

  // Per-page entrance animation
  late AnimationController _heroCtrl;
  late Animation<double> _heroScale;
  late Animation<double> _heroSlideY;
  late Animation<double> _heroFade;

  // Text entrance
  late AnimationController _textCtrl;
  late Animation<double> _textFade;
  late Animation<Offset> _textSlide;

  // Continuous floating animation for the character
  late AnimationController _floatCtrl;

  // Glow pulse
  late AnimationController _glowCtrl;

  static const _pages = [
    _OnboardPage(
      image: 'assets/onboarding/onboard_welcome.png',
      title: 'Welcome to Reasonable Doubt',
      subtitle: 'Your AI-powered legal companion.\nKnow your rights, anywhere in the world.',
      accentColor: AppColors.royalBlue,
      particleColor: AppColors.royalBlue,
    ),
    _OnboardPage(
      image: 'assets/onboarding/onboard_chat.png',
      title: 'AI Legal Chat',
      subtitle: 'Ask any legal question in plain language.\nGet clear, cited answers instantly.',
      accentColor: Color(0xFF3366FF),
      particleColor: Color(0xFF5588FF),
    ),
    _OnboardPage(
      image: 'assets/onboarding/onboard_voice.png',
      title: 'Voice Consultation',
      subtitle: 'Speak naturally with your legal AI.\nLike having a lawyer on speed-dial.',
      accentColor: Color(0xFF0A7D5A),
      particleColor: Color(0xFF0ABFA0),
    ),
    _OnboardPage(
      image: 'assets/onboarding/onboard_rights.png',
      title: 'Know Your Rights',
      subtitle: 'Tailored rights info for 183 countries.\nBe prepared for any situation.',
      accentColor: AppColors.gold,
      particleColor: AppColors.goldLight,
    ),
  ];

  @override
  void initState() {
    super.initState();

    // Hero entrance: scale from behind + slide up + fade
    _heroCtrl = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 900),
    );
    _heroScale = Tween<double>(begin: 0.5, end: 1.0).animate(
      CurvedAnimation(parent: _heroCtrl, curve: Curves.easeOutBack),
    );
    _heroSlideY = Tween<double>(begin: 60, end: 0).animate(
      CurvedAnimation(parent: _heroCtrl, curve: Curves.easeOutCubic),
    );
    _heroFade = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _heroCtrl,
        curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
      ),
    );

    // Text entrance
    _textCtrl = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 700),
    );
    _textFade = CurvedAnimation(parent: _textCtrl, curve: Curves.easeOut);
    _textSlide = Tween<Offset>(
      begin: const Offset(0, 0.4),
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: _textCtrl, curve: Curves.easeOutCubic));

    // Continuous float (subtle bob)
    _floatCtrl = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 3000),
    )..repeat(reverse: true);

    // Glow pulse
    _glowCtrl = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 2000),
    )..repeat(reverse: true);

    // Kick off first page entrance
    _playEntrance();
  }

  void _playEntrance() {
    _heroCtrl.reset();
    _textCtrl.reset();
    _heroCtrl.forward();
    Future.delayed(const Duration(milliseconds: 350), () {
      if (mounted) _textCtrl.forward();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _heroCtrl.dispose();
    _textCtrl.dispose();
    _floatCtrl.dispose();
    _glowCtrl.dispose();
    super.dispose();
  }

  void _next() {
    if (_page < _pages.length - 1) {
      _controller.nextPage(
        duration: const Duration(milliseconds: 600),
        curve: Curves.easeOutCubic,
      );
    } else {
      _finish();
    }
  }

  Future<void> _finish() async {
    final provider = context.read<AppProvider>();
    await provider.auth.completeOnboarding();
    if (!mounted) return;
    Navigator.of(context).pushReplacementNamed('/login');
  }

  @override
  Widget build(BuildContext context) {
    final screenH = MediaQuery.of(context).size.height;
    final screenW = MediaQuery.of(context).size.width;

    return Scaffold(
      backgroundColor: AppColors.navy,
      body: Stack(
        children: [
          // Layer 0: Animated gradient mesh background
          const Positioned.fill(child: GradientMesh()),

          // Layer 1: Particles (color adapts to current page)
          Positioned.fill(
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 800),
              child: ParticleField(
                key: ValueKey(_page),
                count: 50,
                color: _pages[_page].particleColor,
              ),
            ),
          ),

          // Layer 2: Page content
          PageView.builder(
            controller: _controller,
            itemCount: _pages.length,
            onPageChanged: (i) {
              setState(() => _page = i);
              _playEntrance();
            },
            itemBuilder: (context, i) {
              final p = _pages[i];
              return _buildPage(p, screenH, screenW);
            },
          ),

          // Layer 3: Bottom controls (dots + buttons)
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: _buildBottomControls(),
          ),
        ],
      ),
    );
  }

  Widget _buildPage(_OnboardPage p, double screenH, double screenW) {
    return Column(
      children: [
        SizedBox(height: screenH * 0.08),

        // 3D Hero Image Section
        Expanded(
          flex: 5,
          child: _buildHeroSection(p, screenW),
        ),

        // Text Section
        Expanded(
          flex: 3,
          child: _buildTextSection(p),
        ),

        // Space for bottom controls
        SizedBox(height: screenH * 0.14),
      ],
    );
  }

  Widget _buildHeroSection(_OnboardPage p, double screenW) {
    return AnimatedBuilder(
      animation: Listenable.merge([_heroCtrl, _floatCtrl, _glowCtrl]),
      builder: (context, _) {
        // Floating bob
        final floatY = math.sin(_floatCtrl.value * math.pi) * 10;
        // Subtle rotation
        final floatRotZ = math.sin(_floatCtrl.value * math.pi * 2) * 0.015;

        return Transform.translate(
          offset: Offset(0, _heroSlideY.value + floatY),
          child: Transform(
            alignment: Alignment.center,
            transform: Matrix4.identity()
              ..setEntry(3, 2, 0.001) // 3D perspective
              ..scale(_heroScale.value)
              ..rotateZ(floatRotZ),
            child: Opacity(
              opacity: _heroFade.value,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // Glow behind character
                  _buildGlow(p.accentColor),

                  // 3D orbit rings
                  SizedBox(
                    width: screenW * 0.85,
                    height: screenW * 0.85,
                    child: OrbitRings(
                      radius: screenW * 0.35,
                      ringColor: p.accentColor,
                      child: const SizedBox.shrink(),
                    ),
                  ),

                  // Character image with 3D shadow
                  _buildCharacterImage(p),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildGlow(Color color) {
    final pulse = 0.8 + _glowCtrl.value * 0.4;
    return Container(
      width: 280 * pulse,
      height: 280 * pulse,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: RadialGradient(
          colors: [
            color.withValues(alpha: 0.25 * pulse),
            color.withValues(alpha: 0.08),
            Colors.transparent,
          ],
          stops: const [0.0, 0.5, 1.0],
        ),
      ),
    );
  }

  Widget _buildCharacterImage(_OnboardPage p) {
    return Container(
      height: 340,
      width: 260,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(30),
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // Soft 3D shadow beneath character
          Positioned(
            bottom: -5,
            child: Container(
              width: 180,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(100),
                boxShadow: [
                  BoxShadow(
                    color: p.accentColor.withValues(alpha: 0.3),
                    blurRadius: 40,
                    spreadRadius: 5,
                  ),
                ],
              ),
            ),
          ),
          // The character
          Image.asset(
            p.image,
            height: 340,
            fit: BoxFit.contain,
            filterQuality: FilterQuality.high,
          ),
          // Holographic shimmer overlay
          Positioned.fill(
            child: AnimatedBuilder(
              animation: _glowCtrl,
              builder: (context, _) {
                return ShaderMask(
                  shaderCallback: (bounds) {
                    final dx = _glowCtrl.value * 2 - 0.5;
                    return LinearGradient(
                      begin: Alignment(dx - 0.3, -0.5),
                      end: Alignment(dx + 0.3, 0.5),
                      colors: [
                        Colors.transparent,
                        Colors.white.withValues(alpha: 0.08),
                        Colors.transparent,
                      ],
                      stops: const [0.0, 0.5, 1.0],
                    ).createShader(bounds);
                  },
                  blendMode: BlendMode.srcATop,
                  child: Image.asset(
                    p.image,
                    height: 340,
                    fit: BoxFit.contain,
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTextSection(_OnboardPage p) {
    return SlideTransition(
      position: _textSlide,
      child: FadeTransition(
        opacity: _textFade,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 36),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Accent line
              Container(
                width: 40,
                height: 3,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(2),
                  color: p.accentColor,
                  boxShadow: [
                    BoxShadow(
                      color: p.accentColor.withValues(alpha: 0.5),
                      blurRadius: 8,
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 20),

              // Title with gradient
              ShaderMask(
                shaderCallback: (bounds) => LinearGradient(
                  colors: [Colors.white, p.accentColor.withValues(alpha: 0.8)],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                ).createShader(bounds),
                child: Text(
                  p.title,
                  style: AppTypography.displayLg.copyWith(
                    color: Colors.white,
                    height: 1.2,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
              const SizedBox(height: 14),

              // Subtitle with glass card
              ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
                    decoration: BoxDecoration(
                      color: Colors.white.withValues(alpha: 0.06),
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(
                        color: p.accentColor.withValues(alpha: 0.15),
                      ),
                    ),
                    child: Text(
                      p.subtitle,
                      style: AppTypography.bodyLg.copyWith(
                        color: AppColors.textSecondary,
                        height: 1.6,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomControls() {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Animated page indicator
            _buildPageIndicator(),
            const SizedBox(height: 28),

            // Buttons
            Row(
              children: [
                // Back button
                if (_page > 0)
                  _buildGlassButton(
                    'Back',
                    onTap: () => _controller.previousPage(
                      duration: const Duration(milliseconds: 600),
                      curve: Curves.easeOutCubic,
                    ),
                  )
                else
                  const SizedBox(width: 70),

                const Spacer(),

                // Skip
                if (_page < _pages.length - 1)
                  GestureDetector(
                    onTap: _finish,
                    child: Text(
                      'Skip',
                      style: AppTypography.bodyMd.copyWith(
                        color: AppColors.textMuted,
                      ),
                    ),
                  ),

                const SizedBox(width: 16),

                // Next / Get Started — main CTA
                _buildMainButton(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPageIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(_pages.length, (i) {
        final active = i == _page;
        return AnimatedContainer(
          duration: const Duration(milliseconds: 400),
          curve: Curves.easeOutCubic,
          margin: const EdgeInsets.symmetric(horizontal: 4),
          width: active ? 32 : 8,
          height: 8,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            gradient: active
                ? LinearGradient(
                    colors: [
                      _pages[_page].accentColor,
                      _pages[_page].accentColor.withValues(alpha: 0.6),
                    ],
                  )
                : null,
            color: active ? null : AppColors.glassBorder,
            boxShadow: active
                ? [
                    BoxShadow(
                      color: _pages[_page].accentColor.withValues(alpha: 0.4),
                      blurRadius: 8,
                    ),
                  ]
                : null,
          ),
        );
      }),
    );
  }

  Widget _buildGlassButton(String text, {required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.07),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: AppColors.glassBorder),
            ),
            child: Text(
              text,
              style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildMainButton() {
    final isLast = _page == _pages.length - 1;
    final accent = _pages[_page].accentColor;

    return GestureDetector(
      onTap: _next,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 400),
        padding: EdgeInsets.symmetric(
          horizontal: isLast ? 36 : 28,
          vertical: 14,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: isLast
                ? [AppColors.gold, AppColors.goldDark]
                : [accent, accent.withValues(alpha: 0.8)],
          ),
          borderRadius: BorderRadius.circular(14),
          boxShadow: [
            BoxShadow(
              color: (isLast ? AppColors.gold : accent).withValues(alpha: 0.4),
              blurRadius: 20,
              offset: const Offset(0, 6),
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              isLast ? 'Get Started' : 'Next',
              style: AppTypography.bodyMd.copyWith(
                color: isLast ? AppColors.navy : Colors.white,
                fontWeight: FontWeight.w600,
              ),
            ),
            if (isLast) ...[
              const SizedBox(width: 8),
              Icon(
                Icons.arrow_forward_rounded,
                size: 18,
                color: AppColors.navy,
              ),
            ],
          ],
        ),
      ),
    );
  }
}

class _OnboardPage {
  final String image;
  final String title;
  final String subtitle;
  final Color accentColor;
  final Color particleColor;

  const _OnboardPage({
    required this.image,
    required this.title,
    required this.subtitle,
    required this.accentColor,
    required this.particleColor,
  });
}
