import 'package:flutter/material.dart';
import '../core/theme/app_colors.dart';
import '../core/theme/app_typography.dart';

class SpotlightOverlay extends StatefulWidget {
  final List<SpotlightTarget> targets;
  final VoidCallback onComplete;

  const SpotlightOverlay({
    super.key,
    required this.targets,
    required this.onComplete,
  });

  @override
  State<SpotlightOverlay> createState() => _SpotlightOverlayState();
}

class _SpotlightOverlayState extends State<SpotlightOverlay>
    with SingleTickerProviderStateMixin {
  int _current = 0;
  late AnimationController _controller;
  late Animation<double> _fade;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );
    _fade = CurvedAnimation(parent: _controller, curve: Curves.easeOut);
    _controller.forward();
  }

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

  void _next() {
    if (_current < widget.targets.length - 1) {
      _controller.reverse().then((_) {
        setState(() => _current++);
        _controller.forward();
      });
    } else {
      _controller.reverse().then((_) => widget.onComplete());
    }
  }

  void _prev() {
    if (_current > 0) {
      _controller.reverse().then((_) {
        setState(() => _current--);
        _controller.forward();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final target = widget.targets[_current];
    final screenH = MediaQuery.of(context).size.height;
    final screenW = MediaQuery.of(context).size.width;

    // Resolve rect from GlobalKey if provided
    Rect targetRect = target.rect ?? Rect.zero;
    if (target.key != null) {
      final renderBox = target.key!.currentContext?.findRenderObject() as RenderBox?;
      if (renderBox != null && renderBox.hasSize) {
        final offset = renderBox.localToGlobal(Offset.zero);
        targetRect = Rect.fromLTWH(
          offset.dx - target.padding,
          offset.dy - target.padding,
          renderBox.size.width + target.padding * 2,
          renderBox.size.height + target.padding * 2,
        );
      }
    }

    final center = targetRect.center;
    final radius = (targetRect.longestSide / 2) + 12;

    // Position tooltip above or below the spotlight
    final spaceBelow = screenH - targetRect.bottom;
    final showBelow = spaceBelow > 220;
    final tooltipTop = showBelow
        ? targetRect.bottom + 20
        : targetRect.top - 200;

    return FadeTransition(
      opacity: _fade,
      child: GestureDetector(
        onTap: _next,
        child: Stack(
          children: [
            // Dim overlay with spotlight cutout
            Positioned.fill(
              child: CustomPaint(
                painter: _SpotlightPainter(
                  targetRect: targetRect,
                  borderRadius: target.borderRadius,
                ),
              ),
            ),
            // Tooltip card
            Positioned(
              left: 20,
              right: 20,
              top: tooltipTop.clamp(60.0, screenH - 240),
              child: Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: AppColors.navy.withValues(alpha: 0.95),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: AppColors.glassBorderStrong),
                  boxShadow: [
                    BoxShadow(
                      color: AppColors.royalBlue.withValues(alpha: 0.25),
                      blurRadius: 30,
                      spreadRadius: 2,
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // Step indicator
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                          decoration: BoxDecoration(
                            color: AppColors.royalBlue.withValues(alpha: 0.15),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            'Step ${_current + 1} of ${widget.targets.length}',
                            style: AppTypography.bodySm.copyWith(
                              color: AppColors.royalBlue,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        const Spacer(),
                        GestureDetector(
                          onTap: () => widget.onComplete(),
                          child: Text('Skip', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                        ),
                      ],
                    ),
                    const SizedBox(height: 14),
                    Text(target.title,
                        style: AppTypography.headingLg.copyWith(color: Colors.white)),
                    const SizedBox(height: 8),
                    Text(target.description,
                        style: AppTypography.bodyMd.copyWith(
                          color: AppColors.textSecondary,
                          height: 1.5,
                        )),
                    const SizedBox(height: 18),
                    // Progress dots + buttons
                    Row(
                      children: [
                        // Progress dots
                        ...List.generate(widget.targets.length, (i) {
                          return Container(
                            width: i == _current ? 20 : 6,
                            height: 6,
                            margin: const EdgeInsets.only(right: 4),
                            decoration: BoxDecoration(
                              color: i == _current ? AppColors.gold : AppColors.glassBorder,
                              borderRadius: BorderRadius.circular(3),
                            ),
                          );
                        }),
                        const Spacer(),
                        if (_current > 0)
                          GestureDetector(
                            onTap: _prev,
                            child: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                              margin: const EdgeInsets.only(right: 8),
                              decoration: BoxDecoration(
                                color: AppColors.glassSurface,
                                borderRadius: BorderRadius.circular(10),
                                border: Border.all(color: AppColors.glassBorder),
                              ),
                              child: Text('Back', style: AppTypography.button.copyWith(color: Colors.white70, fontSize: 13)),
                            ),
                          ),
                        GestureDetector(
                          onTap: _next,
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
                            decoration: BoxDecoration(
                              gradient: AppColors.blueGradient,
                              borderRadius: BorderRadius.circular(10),
                              boxShadow: [
                                BoxShadow(
                                  color: AppColors.royalBlue.withValues(alpha: 0.3),
                                  blurRadius: 12,
                                  offset: const Offset(0, 3),
                                ),
                              ],
                            ),
                            child: Text(
                              _current < widget.targets.length - 1 ? 'Next' : 'Get Started',
                              style: AppTypography.button.copyWith(color: Colors.white, fontSize: 13),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _SpotlightPainter extends CustomPainter {
  final Rect targetRect;
  final double borderRadius;

  _SpotlightPainter({required this.targetRect, this.borderRadius = 16});

  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..addRect(Rect.fromLTWH(0, 0, size.width, size.height));

    if (targetRect != Rect.zero) {
      path.addRRect(RRect.fromRectAndRadius(targetRect, Radius.circular(borderRadius)));
    }
    path.fillType = PathFillType.evenOdd;

    canvas.drawPath(
      path,
      Paint()..color = Colors.black.withValues(alpha: 0.8),
    );

    // Glow border around the cutout
    if (targetRect != Rect.zero) {
      canvas.drawRRect(
        RRect.fromRectAndRadius(
          targetRect.inflate(2),
          Radius.circular(borderRadius + 2),
        ),
        Paint()
          ..color = AppColors.royalBlue.withValues(alpha: 0.5)
          ..style = PaintingStyle.stroke
          ..strokeWidth = 2.5,
      );
      // Additional gold outer glow
      canvas.drawRRect(
        RRect.fromRectAndRadius(
          targetRect.inflate(6),
          Radius.circular(borderRadius + 6),
        ),
        Paint()
          ..color = AppColors.gold.withValues(alpha: 0.15)
          ..style = PaintingStyle.stroke
          ..strokeWidth = 1.5,
      );
    }
  }

  @override
  bool shouldRepaint(covariant _SpotlightPainter old) =>
      old.targetRect != targetRect || old.borderRadius != borderRadius;
}

class SpotlightTarget {
  final GlobalKey? key;
  final Rect? rect;
  final double padding;
  final double borderRadius;
  final String title;
  final String description;

  const SpotlightTarget({
    this.key,
    this.rect,
    this.padding = 8,
    this.borderRadius = 16,
    required this.title,
    required this.description,
  });
}
