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

import '../blocs/ptz/ptz_bloc.dart';
import '../blocs/ptz/ptz_event.dart';
import '../blocs/monitor/monitor_bloc.dart';
import '../blocs/monitor/monitor_state.dart';

class PresetButtons extends StatelessWidget {
  final int presetCount;

  const PresetButtons({super.key, this.presetCount = 8});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MonitorBloc, MonitorBlocState>(
      builder: (context, monitorState) {
        final cameraId = monitorState.selectedMonitorCamera;
        final isEnabled = cameraId != null && cameraId > 0;

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Text(
                'PRESETS',
                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
              ),
            ),
            Wrap(
              spacing: 4,
              runSpacing: 4,
              children: List.generate(presetCount, (index) {
                final presetId = index + 1;
                return _PresetButton(
                  presetId: presetId,
                  isEnabled: isEnabled,
                  onPressed: isEnabled
                      ? () => context.read<PtzBloc>().add(
                            PtzGoToPreset(cameraId: cameraId, preset: presetId),
                          )
                      : null,
                );
              }),
            ),
          ],
        );
      },
    );
  }
}

class _PresetButton extends StatelessWidget {
  final int presetId;
  final bool isEnabled;
  final VoidCallback? onPressed;

  const _PresetButton({
    required this.presetId,
    required this.isEnabled,
    this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 44,
      height: 36,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: isEnabled
              ? Theme.of(context).colorScheme.secondaryContainer
              : Theme.of(context).colorScheme.surfaceContainerHighest,
          foregroundColor: isEnabled
              ? Theme.of(context).colorScheme.onSecondaryContainer
              : Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.4),
          padding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4),
          ),
        ),
        child: Text(
          '$presetId',
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}
