import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:nearle/views/helpers/constants/Colorconstants.dart';
import 'package:nearle/views/helpers/constants/Font_constant.dart';

class OrderAlertSoundPage extends StatefulWidget {
  const OrderAlertSoundPage({super.key});

  @override
  State<OrderAlertSoundPage> createState() => _OrderAlertSoundPageState();
}

class _OrderAlertSoundPageState extends State<OrderAlertSoundPage> {
  static const String _prefsKey = 'order_alert_sound';
  static const String _defaultSound = 'assets/audio/alert-1.mp3';

  final AudioPlayer _player = AudioPlayer();
  String _selected = _defaultSound;
  bool _loading = true;

  // Available sounds from assets/audio/ folder
  final List<_SoundOption> _options = const [
    _SoundOption(
      label: 'Alert 1 (Default)',
      assetPath: 'assets/audio/alert-1.mp3',
    ),
    _SoundOption(label: 'Alert 2', assetPath: 'assets/audio/alert-2.mp3'),
    _SoundOption(label: 'Alert 3', assetPath: 'assets/audio/alert-3.mp3'),
    _SoundOption(label: 'Alert 4', assetPath: 'assets/audio/alert-4.mp3'),
    _SoundOption(label: 'Alert 5', assetPath: 'assets/audio/alert-5.mp3'),
    _SoundOption(label: 'Alert 6', assetPath: 'assets/audio/alert-6.mp3'),
    _SoundOption(label: 'Alert 7', assetPath: 'assets/audio/alert-7.mp3'),
    _SoundOption(label: 'Alert 8', assetPath: 'assets/audio/alert-8.mp3'),
    _SoundOption(label: 'Alert 9', assetPath: 'assets/audio/alert-9.mp3'),
    _SoundOption(label: 'Alert 10', assetPath: 'assets/audio/alert-10.mp3'),
  ];

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

  Future<void> _loadSelection() async {
    final prefs = await SharedPreferences.getInstance();
    final saved = prefs.getString(_prefsKey);
    setState(() {
      _selected = (saved != null && saved.isNotEmpty) ? saved : _defaultSound;
      _loading = false;
    });
  }

  Future<void> _saveSelection(BuildContext context, String assetPath) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_prefsKey, assetPath);
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('Order alert sound updated'),
        behavior: SnackBarBehavior.floating,
        margin: const EdgeInsets.all(16),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  Future<void> _preview(BuildContext context, String assetPath) async {
    try {
      await _player.stop();
      await _player.play(AssetSource(assetPath.replaceFirst('assets/', '')));
      // Note: AssetSource expects relative to assets/ root; hence replaceFirst
    } catch (_) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Preview unavailable for: $assetPath'),
          behavior: SnackBarBehavior.floating,
          margin: const EdgeInsets.all(16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: ColorConstants.primaryColor,
        centerTitle: true,
        toolbarHeight: 70, // :small_blue_diamond: increases app bar height
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ), // :small_blue_diamond: white back arrow
          onPressed: () {
            Navigator.pop(context); // goes back to previous screen
          },
        ),
        title: const Text(
          'Orders alert Sound',
          style: TextStyle(
            fontSize: 26, // :small_blue_diamond: larger font size
            color: Colors.white, // :small_blue_diamond: white text
            fontWeight: FontWeight.bold,
            letterSpacing: 1.2,
          ),
        ),
        elevation: 4,
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 10,
                  ),
                  color: Colors.grey.shade200,
                  child: Row(
                    children: [
                      const Icon(Icons.volume_up, size: 20),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          'Current: ${_options.firstWhereOrNull((o) => o.assetPath == _selected)?.label ?? 'Unknown'}',
                          style: TextStyle(
                            fontFamily: FontConstants.fontFamily,
                            fontWeight: FontWeight.w600,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const Text(
                        'Tap a sound to select',
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                const Divider(height: 1),
                Expanded(
                  child: ListView.separated(
                    itemCount: _options.length,
                    separatorBuilder: (_, __) => const Divider(height: 1),
                    itemBuilder: (context, index) {
                      final opt = _options[index];
                      final isSelected = _selected == opt.assetPath;
                      return ListTile(
                        title: Text(
                          opt.label,
                          style: TextStyle(
                            fontFamily: FontConstants.fontFamily,
                          ),
                        ),
                        leading: Radio<String>(
                          value: opt.assetPath,
                          groupValue: _selected,
                          onChanged: (value) {
                            if (value == null) return;
                            setState(() => _selected = value);
                            _saveSelection(context, value);
                          },
                        ),
                        trailing: IconButton(
                          icon: const Icon(Icons.play_arrow),
                          onPressed: () => _preview(context, opt.assetPath),
                        ),
                        onTap: () {
                          setState(() => _selected = opt.assetPath);
                          _saveSelection(context, opt.assetPath);
                        },
                        subtitle: isSelected
                            ? const Text(
                                'Selected',
                                style: TextStyle(fontSize: 12),
                              )
                            : null,
                      );
                    },
                  ),
                ),
              ],
            ),
    );
  }
}

class _SoundOption {
  final String label;
  final String assetPath;
  const _SoundOption({required this.label, required this.assetPath});
}
