import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../managers/sound_manager.dart';

class SettingsPage extends StatelessWidget {
  const SettingsPage({super.key});

  void _showVolumeControl(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return ValueListenableBuilder<double>(
          valueListenable: SoundManager().volumeNotifier,
          builder: (context, currentVolume, _) {
            return Container(
              padding: const EdgeInsets.all(24),
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(30)),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 40,
                    height: 4,
                    margin: const EdgeInsets.only(bottom: 24),
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2),
                    ),
                  ),
                  const Text(
                    'Volume Control',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 30),
                  Row(
                    children: [
                      Icon(Icons.volume_mute_rounded, color: Colors.grey[400]),
                      Expanded(
                        child: Slider(
                          value: currentVolume,
                          activeColor: const Color(0xFF6C63FF),
                          inactiveColor: Colors.grey[200],
                          onChanged: (value) {
                            SoundManager().setVolume(value);
                          },
                        ),
                      ),
                      Icon(Icons.volume_up_rounded, color: const Color(0xFF6C63FF)),
                    ],
                  ),
                  const SizedBox(height: 10),
                  Text(
                    '${(currentVolume * 100).toInt()}%',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF6C63FF),
                    ),
                  ),
                  const SizedBox(height: 30),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF6C63FF),
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                        elevation: 0,
                      ),
                      child: const Text('Done', style: TextStyle(fontWeight: FontWeight.bold)),
                    ),
                  ),
                  const SizedBox(height: 20),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void _shareApp(BuildContext context) async {
    const String appUrl = "https://play.google.com/store/apps/details?id=com.example.pranksounds";
    const String message = "Check out this funny Prank Sounds app! 🤣\n$appUrl";
    try {
      await Share.share(message);
    } catch (e) {
      if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not share: $e')));
    }
  }

  void _openPrivacyPolicy(BuildContext context) async {
    final Uri url = Uri.parse("https://www.google.com/policies/privacy/");
    try {
      if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
        throw Exception('Could not launch $url');
      }
    } catch (e) {
      if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Could not open link: $e')));
    }
  }

  void _rateUs(BuildContext context) async {
    final Uri url = Uri.parse("https://play.google.com/store/apps/details?id=com.example.pranksounds");
    try {
      if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
        throw Exception('Could not launch store');
      }
    } catch (e) {
      if (context.mounted) ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Could not open store')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            title: const Text('Settings'),
            pinned: true,
            backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          ),
          SliverToBoxAdapter(
            child: Column(
              children: [
                const SizedBox(height: 10),
                _buildProfileCard(),
                const SizedBox(height: 30),
                _buildSettingsGroup('GENERAL', [
                  // Volume Setting with Listener
                  ValueListenableBuilder<double>(
                    valueListenable: SoundManager().volumeNotifier,
                    builder: (context, volume, _) {
                      return _buildSettingItem(
                        Icons.volume_up_rounded,
                        'Volume',
                        trailing: '${(volume * 100).toInt()}%',
                        onTap: () => _showVolumeControl(context),
                      );
                    },
                  ),
                  // Loop Setting with Listener
                  ValueListenableBuilder<bool>(
                    valueListenable: SoundManager().loopNotifier,
                    builder: (context, isLooping, _) {
                      return _buildSettingItem(
                        Icons.loop_rounded,
                        'Loop Sound',
                        isSwitch: true,
                        switchValue: isLooping,
                        onSwitchChanged: (val) {
                          SoundManager().setLooping(val);
                        },
                      );
                    },
                  ),
                ]),
                _buildSettingsGroup('SUPPORT', [
                  _buildSettingItem(Icons.star_rounded, 'Rate Us', onTap: () => _rateUs(context)),
                  _buildSettingItem(Icons.share_rounded, 'Share App', onTap: () => _shareApp(context)),
                  _buildSettingItem(Icons.privacy_tip_rounded, 'Privacy Policy', onTap: () => _openPrivacyPolicy(context)),
                ]),
                const SizedBox(height: 40),
                Text('Version 2.0.1 (Build 102)', style: TextStyle(color: Colors.grey[400], fontSize: 12)),
                const SizedBox(height: 120),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildProfileCard() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF6C63FF), Color(0xFF30B0C7)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF6C63FF).withOpacity(0.4),
            blurRadius: 20,
            offset: const Offset(0, 10),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(3),
            decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
            child: const CircleAvatar(
              radius: 26,
              backgroundColor: Colors.grey,
              child: Icon(Icons.person, color: Colors.white),
            ),
          ),
          const SizedBox(width: 16),
          const Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Prank Master', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)),
                Text('Pro Member', style: TextStyle(color: Colors.white70, fontSize: 13)),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(100),
            ),
            child: const Text('PRO', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12)),
          )
        ],
      ),
    );
  }

  Widget _buildSettingsGroup(String title, List<Widget> children) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 10, bottom: 10),
            child: Text(
              title,
              style: TextStyle(color: Colors.grey[500], fontWeight: FontWeight.bold, fontSize: 12, letterSpacing: 1.2),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10)],
            ),
            child: Column(children: children),
          ),
        ],
      ),
    );
  }

  Widget _buildSettingItem(
      IconData icon,
      String title,
      {
        String? trailing,
        bool isSwitch = false,
        bool switchValue = false,
        ValueChanged<bool>? onSwitchChanged,
        VoidCallback? onTap
      }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: isSwitch ? () => onSwitchChanged?.call(!switchValue) : onTap,
        borderRadius: BorderRadius.circular(20),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xFFF4F6FD),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Icon(icon, color: const Color(0xFF1D1D35), size: 20),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Text(title, style: const TextStyle(fontWeight: FontWeight.w600, color: Color(0xFF1D1D35))),
              ),
              if (isSwitch)
                SizedBox(
                  height: 24,
                  child: Switch(
                    value: switchValue,
                    activeColor: const Color(0xFF6C63FF),
                    onChanged: onSwitchChanged,
                  ),
                )
              else if (trailing != null)
                Text(trailing, style: TextStyle(color: Colors.grey[400], fontWeight: FontWeight.bold))
              else
                Icon(Icons.chevron_right_rounded, color: Colors.grey[300]),
            ],
          ),
        ),
      ),
    );
  }
}
