import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import '../styles/theme.dart';

class KWSlider extends StatefulWidget {
  final double min;
  final double max;
  final double initialValue;
  final ValueChanged<double>? onChanged;

  const KWSlider({
    super.key,
    this.min = 1.0,
    this.max = 20.0,
    this.initialValue = 3.0,
    this.onChanged,
  });

  @override
  State<KWSlider> createState() => _KWSliderState();
}

class _KWSliderState extends State<KWSlider> {
  late double _value;

  @override
  void initState() {
    super.initState();
    _value = widget.initialValue.clamp(widget.min, widget.max);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final double sliderWidth = constraints.maxWidth;

        const double sliderHeight = 12;
        const primaryColor = AppColors.bgColorDark;
        const secondaryColor = AppColors.grayTintStroke;

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            KWSliderTooltip(
              text: '${_value.toInt()} y',
              leftPosition:
                  ((_value - widget.min) / (widget.max - widget.min)) *
                      sliderWidth,
              sliderWidth: sliderWidth,
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 15),
              height: 60,
              child: Stack(
                alignment: Alignment.centerLeft,
                children: [
                  Container(
                    height: sliderHeight,
                    width: sliderWidth,
                    decoration: BoxDecoration(
                      color: secondaryColor,
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  Container(
                    height: sliderHeight,
                    width: ((_value - widget.min) / (widget.max - widget.min)) *
                        sliderWidth,
                    decoration: BoxDecoration(
                      color: primaryColor,
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  Positioned(
                    left: ((_value - widget.min) / (widget.max - widget.min)) *
                            sliderWidth -
                        12,
                    child: SliderHead(
                      color: primaryColor,
                      onPanUpdate: (details) {
                        setState(() {
                          final newValue = _value +
                              (details.delta.dx / sliderWidth) *
                                  (widget.max - widget.min);
                          _value = newValue.clamp(widget.min, widget.max);
                          widget.onChanged?.call(_value);
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('${widget.min.toInt()} year'),
                Text('${widget.max.toInt()} years'),
              ],
            ),
          ],
        );
      },
    );
  }
}

class KWSliderTooltip extends StatelessWidget {
  final String text;
  final double leftPosition;
  final double sliderWidth;

  const KWSliderTooltip({
    super.key,
    required this.text,
    required this.leftPosition,
    required this.sliderWidth,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(
        left: (leftPosition - 24).clamp(0, sliderWidth - 48),
      ),
      width: 48,
      child: CustomPaint(
        painter: TooltipPainter(),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Text(
              text,
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class TooltipPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = const Color(0xFF001F2D);
    final path = Path();

    path.addRRect(
      RRect.fromRectAndRadius(
        const Rect.fromLTWH(0, 0, 48, 30),
        const Radius.circular(15),
      ),
    );

    const double triangleWidth = 10;
    const double triangleHeight = 6;
    const double centerX = 24;

    path.moveTo(centerX - triangleWidth / 2, 30);
    path.quadraticBezierTo(
      centerX,
      40 + triangleHeight / 3,
      centerX + triangleWidth / 2,
      30,
    );
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

class SliderHead extends StatelessWidget {
  final double size;
  final Color color;
  final VoidCallback? onPanStart;
  final Function(DragUpdateDetails)? onPanUpdate;

  const SliderHead({
    super.key,
    this.size = 24.0,
    required this.color,
    this.onPanStart,
    this.onPanUpdate,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      dragStartBehavior: DragStartBehavior.down,
      onPanUpdate: onPanUpdate,
      onPanStart: (_) => onPanStart?.call(),
      child: Container(
        width: size,
        height: size,
        decoration: BoxDecoration(
          color: color,
          border: Border.all(
            color: Colors.white,
            width: 5,
          ),
          shape: BoxShape.circle,
          boxShadow: const [
            BoxShadow(
              color: Color(0x08000000),
              offset: Offset(0, 1),
              blurRadius: 2,
              spreadRadius: 0,
            ),
            BoxShadow(
              color: Color(0x08000000),
              offset: Offset(0, 4),
              blurRadius: 4,
              spreadRadius: 0,
            ),
          ],
        ),
      ),
    );
  }
}
