import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/schedule_device/bloc/schedule_bloc.dart';
import 'package:syncrow_web/pages/device_managment/water_heater/models/water_heater_status_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class CountdownInchingView extends StatefulWidget {
  final String deviceId;
  const CountdownInchingView({super.key, required this.deviceId});

  @override
  State<CountdownInchingView> createState() => _CountdownInchingViewState();
}

class _CountdownInchingViewState extends State<CountdownInchingView> {
  late FixedExtentScrollController _hoursController;
  late FixedExtentScrollController _minutesController;
  late FixedExtentScrollController _secondsController;

  int _lastHours = -1;
  int _lastMinutes = -1;
  int _lastSeconds = -1;

  @override
  void initState() {
    super.initState();
    _hoursController = FixedExtentScrollController();
    _minutesController = FixedExtentScrollController();
    _secondsController = FixedExtentScrollController();
  }

  @override
  void dispose() {
    _hoursController.dispose();
    _minutesController.dispose();
    _secondsController.dispose();
    super.dispose();
  }

  void _updateControllers(
      int displayHours, int displayMinutes, int displaySeconds) {
    if (_lastHours != displayHours) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_hoursController.hasClients) {
          _hoursController.jumpToItem(displayHours);
        }
      });
      _lastHours = displayHours;
    }
    if (_lastMinutes != displayMinutes) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_minutesController.hasClients) {
          _minutesController.jumpToItem(displayMinutes);
        }
      });
      _lastMinutes = displayMinutes;
    }
    // Update seconds controller
    if (_lastSeconds != displaySeconds) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_secondsController.hasClients) {
          _secondsController.jumpToItem(displaySeconds);
        }
      });
      _lastSeconds = displaySeconds;
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ScheduleBloc, ScheduleState>(
      builder: (context, state) {
        if (state is! ScheduleLoaded) return const SizedBox.shrink();
        final isCountDown = state.scheduleMode == ScheduleModes.countdown;
        final isActive =
            isCountDown ? state.isCountdownActive : state.isInchingActive;

        final displayHours =
            isActive && state.countdownRemaining != Duration.zero
                ? state.countdownRemaining.inHours
                : (isCountDown ? state.countdownHours : state.inchingHours);

        final displayMinutes =
            isActive && state.countdownRemaining != Duration.zero
                ? state.countdownRemaining.inMinutes.remainder(60)
                : (isCountDown ? state.countdownMinutes : state.inchingMinutes);

        final displaySeconds =
            isActive && state.countdownRemaining != Duration.zero
                ? state.countdownRemaining.inSeconds.remainder(60)
                : (isCountDown ? (state.countdownSeconds ?? 0) : 0);

        _updateControllers(displayHours, displayMinutes, displaySeconds);

        if (isActive &&
            displayHours == 0 &&
            displayMinutes == 0 &&
            displaySeconds == 0) {
          context.read<ScheduleBloc>().add(
                StopScheduleEvent(
                  mode: ScheduleModes.countdown,
                  deviceId: widget.deviceId,
                  countdownCode: '',
                ),
              );
        }

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              isCountDown ? 'Countdown:' : 'Inching:',
              style: context.textTheme.bodySmall!.copyWith(
                fontSize: 13,
                color: ColorsManager.grayColor,
              ),
            ),
            const SizedBox(height: 8),
            Visibility(
              visible: !isCountDown,
              child: const Text(
                'Once enabled this feature, each time the device is turned on, '
                'it will automatically turn off after a preset time.',
              ),
            ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildPickerColumn(
                  context,
                  'h',
                  displayHours,
                  100,
                  _hoursController,
                  (value) {
                    if (!isActive) {
                      context.read<ScheduleBloc>().add(UpdateCountdownTimeEvent(
                            hours: value,
                            minutes: displayMinutes,
                            seconds: displaySeconds,
                          ));
                    }
                  },
                  isActive: isActive,
                ),
                const SizedBox(width: 10),
                _buildPickerColumn(
                  context,
                  'm',
                  displayMinutes,
                  60,
                  _minutesController,
                  (value) {
                    if (!isActive) {
                      context.read<ScheduleBloc>().add(UpdateCountdownTimeEvent(
                            hours: displayHours,
                            minutes: value,
                            seconds: displaySeconds,
                          ));
                    }
                  },
                  isActive: isActive,
                ),
                const SizedBox(width: 10),
                if (isActive)
                  _buildPickerColumn(
                    context,
                    's',
                    displaySeconds,
                    60,
                    _secondsController,
                    (value) {
                      if (!isActive) {
                        context
                            .read<ScheduleBloc>()
                            .add(UpdateCountdownTimeEvent(
                              hours: displayHours,
                              minutes: displayMinutes,
                              seconds: value,
                            ));
                      }
                    },
                    isActive: isActive,
                  ),
              ],
            ),
          ],
        );
      },
    );
  }

  Widget _buildPickerColumn(
    BuildContext context,
    String label,
    int initialValue,
    int itemCount,
    FixedExtentScrollController controller,
    ValueChanged<int> onSelected, {
    required bool isActive,
  }) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          height: 40,
          width: 80,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
            color: ColorsManager.boxColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: ListWheelScrollView.useDelegate(
            controller: controller,
            itemExtent: 40.0,
            physics: isActive
                ? const NeverScrollableScrollPhysics()
                : const FixedExtentScrollPhysics(),
            onSelectedItemChanged: isActive ? null : onSelected,
            childDelegate: ListWheelChildBuilderDelegate(
              builder: (context, index) {
                return Center(
                  child: Text(
                    index.toString().padLeft(2, '0'),
                    style: TextStyle(
                      fontSize: 24,
                      color: isActive ? ColorsManager.grayColor : Colors.black,
                    ),
                  ),
                );
              },
              childCount: itemCount,
            ),
          ),
        ),
        const SizedBox(width: 8),
        Text(
          label,
          style: const TextStyle(
            color: ColorsManager.grayColor,
            fontSize: 18,
          ),
        ),
      ],
    );
  }
}
