import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/presentation/symptoms_checker/user_info_selection/widgets/triangle_indicator.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';

class ThreeColumnDatePicker extends StatefulWidget {
  final DateTime initialDate;
  final ValueChanged<DateTime>? onDateChanged;

  // Feedback config
  final bool enableHaptic;
  final bool enableSound;
  final Duration feedbackDebounce;

  const ThreeColumnDatePicker({
    super.key,
    required this.initialDate,
    this.onDateChanged,
    this.enableHaptic = true,
    this.enableSound = true,
    this.feedbackDebounce = const Duration(milliseconds: 80),
  });

  @override
  State<ThreeColumnDatePicker> createState() => _ThreeColumnDatePickerState();
}

class _ThreeColumnDatePickerState extends State<ThreeColumnDatePicker> {
  static const int yearRange = 100;
  static const double _defaultItemExtent = 48.0; // will be scaled with .h

  late final List<String> _days;
  late final List<String> _months;
  late final List<int> _years;

  late FixedExtentScrollController _dayController;
  late FixedExtentScrollController _monthController;
  late FixedExtentScrollController _yearController;

  int _selectedDay = 0;
  int _selectedMonth = 0;
  int _selectedYearIndex = 0;

  // Debounce timer used for playing feedback only after small pause
  Timer? _feedbackTimer;

  double get _itemExtent => _defaultItemExtent.h;

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

    _days = List.generate(31, (i) => (i + 1).toString().padLeft(2, '0'));
    _months = const ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    final currentYear = DateTime.now().year;
    _years = List.generate(yearRange, (i) => currentYear - i);

    _selectedDay = (widget.initialDate.day - 1).clamp(0, _days.length - 1);
    _selectedMonth = (widget.initialDate.month - 1).clamp(0, _months.length - 1);
    _selectedYearIndex = _years.indexOf(widget.initialDate.year);
    if (_selectedYearIndex == -1) _selectedYearIndex = 0;

    _dayController = FixedExtentScrollController(initialItem: _selectedDay);
    _monthController = FixedExtentScrollController(initialItem: _selectedMonth);
    _yearController = FixedExtentScrollController(initialItem: _selectedYearIndex);
  }

  @override
  void dispose() {
    _feedbackTimer?.cancel();
    _dayController.dispose();
    _monthController.dispose();
    _yearController.dispose();
    super.dispose();
  }

  void _emitDate() {
    final day = int.parse(_days[_selectedDay]);
    final month = _selectedMonth + 1;
    final year = _years[_selectedYearIndex];
    final date = DateTime(year, month, day);
    widget.onDateChanged?.call(date);
  }

  // Schedule haptic + sound feedback with debounce (prevents spamming during fling)
  void _scheduleFeedback() {
    if (!(widget.enableHaptic || widget.enableSound)) return;

    _feedbackTimer?.cancel();
    _feedbackTimer = Timer(widget.feedbackDebounce, () {
      // Haptic
      if (widget.enableHaptic) {
        // selection click is lightweight and appropriate for wheel ticks
        HapticFeedback.selectionClick();
      }
      // Sound
      if (widget.enableSound) {
        // simple system click - note: may be muted by device settings
        SystemSound.play(SystemSoundType.click);
      }
    });
  }

  Widget _wheel({
    required FixedExtentScrollController controller,
    required int itemCount,
    required Widget Function(int index, bool selected) itemBuilder,
    required ValueChanged<int> onSelectedItemChanged,
    required int currentlySelectedIndex,
  }) {
    return Expanded(
      child: SizedBox(
        height: _itemExtent * 5, // show ~5 rows
        child: ListWheelScrollView.useDelegate(
          controller: controller,
          itemExtent: _itemExtent,
          physics: const BouncingScrollPhysics(),
          diameterRatio: 2.2,
          squeeze: 1.2,
          perspective: 0.004,
          // overAndUnderCenterOpacity: 0.6,
          onSelectedItemChanged: (i) {
            // update selected index, emit date and schedule feedback
            onSelectedItemChanged(i);
            _scheduleFeedback();
          },
          childDelegate: ListWheelChildBuilderDelegate(
            builder: (context, index) {
              if (index < 0 || index >= itemCount) return null;
              final bool selected = index == currentlySelectedIndex;
              return Center(child: itemBuilder(index, selected));
            },
            childCount: itemCount,
          ),
        ),
      ),
    );
  }

  Widget _styledText(String text, bool selected) {
    return Text(
      text,
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: selected ? 22.f : 20.f,
        fontWeight: selected ? FontWeight.w600 : FontWeight.w600,
        color: selected ? AppColors.textColor : AppColors.greyTextColor.withValues(alpha: 0.9),
        height: 1.0,
        fontFamily: "Poppins",
        letterSpacing: selected ? -0.02 * 30 : -0.02 * 18,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final pickerHeight = _itemExtent * 5;
    final pointerSize = 20.w;
    final pointerTop = (pickerHeight / 2) - (pointerSize / 2);

    return LayoutBuilder(builder: (context, constraints) {
      return SizedBox(
        height: pickerHeight,
        child: Stack(
          children: [
            Row(
              children: [
                // Day wheel
                _wheel(
                  controller: _dayController,
                  itemCount: _days.length,
                  currentlySelectedIndex: _selectedDay,
                  onSelectedItemChanged: (i) {
                    setState(() => _selectedDay = i);
                    _emitDate();
                  },
                  itemBuilder: (index, selected) => _styledText(_days[index], selected),
                ),

                // Month wheel
                _wheel(
                  controller: _monthController,
                  itemCount: _months.length,
                  currentlySelectedIndex: _selectedMonth,
                  onSelectedItemChanged: (i) {
                    setState(() => _selectedMonth = i);
                    _emitDate();
                  },
                  itemBuilder: (index, selected) => _styledText(_months[index], selected),
                ),

                // Year wheel
                _wheel(
                  controller: _yearController,
                  itemCount: _years.length,
                  currentlySelectedIndex: _selectedYearIndex,
                  onSelectedItemChanged: (i) {
                    setState(() => _selectedYearIndex = i);
                    _emitDate();
                  },
                  itemBuilder: (index, selected) => _styledText(_years[index].toString(), selected),
                ),
              ],
            ),

            // subtle center overlay (optional — keeps layout consistent & highlights center row)
            Positioned.fill(
              child: IgnorePointer(
                child: Center(
                  child: SizedBox(
                    height: _itemExtent,
                  ),
                ),
              ),
            ),

            // left red triangular pointer aligned to center row
            Positioned(
              left: 0.w,
              top: pointerTop,
              child: TriangleIndicator(
                pointerSize: pointerSize,
                // your TriangleIndicator supports direction param; use left as in the original
                // if your TriangleIndicator doesn't accept direction, remove the param
                direction: TriangleDirection.left,
              ),
            ),
          ],
        ),
      );
    });
  }
}
