import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:share_plus/share_plus.dart';
import 'package:aesthetica_wallpaper/models/app_settings.dart';

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

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  AppSettings _settings = AppSettings();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Settings'),
        backgroundColor: Colors.grey[900],
        elevation: 0,
      ),
      body: ListView(
        padding: const EdgeInsets.fromLTRB(
          16,
          16,
          16,
          100,
        ), // 增加底部内边距避免被底部导航栏遮挡
        children: [
          // 应用信息卡片
          _buildAppInfoCard(),
          const SizedBox(height: 24),

          // 壁纸设置
          _buildSectionTitle('Wallpaper'),
          _buildSettingsCard([
            _buildSwitchTile(
              title: 'Auto Save',
              subtitle: 'Automatically save recipes',
              value: _settings.autoSave,
              onChanged: (value) {
                setState(() {
                  _settings = _settings.copyWith(autoSave: value);
                });
              },
            ),
            _buildDivider(),
            _buildSliderTile(
              title: 'Image Quality',
              subtitle: '${(_settings.imageQuality * 100).toInt()}%',
              value: _settings.imageQuality,
              onChanged: (value) {
                setState(() {
                  _settings = _settings.copyWith(imageQuality: value);
                });
              },
            ),
          ]),

          const SizedBox(height: 24),

          // 通知设置
          _buildSectionTitle('Notifications'),
          _buildSettingsCard([
            _buildSwitchTile(
              title: 'Push Notifications',
              subtitle: 'Receive app notifications',
              value: _settings.notifications,
              onChanged: (value) {
                setState(() {
                  _settings = _settings.copyWith(notifications: value);
                });
              },
            ),
          ]),

          const SizedBox(height: 24),

          // Other settings
          _buildSectionTitle('Other'),
          _buildSettingsCard([
            _buildListTile(
              title: 'Share App',
              subtitle: 'Share MoodCanvas:Walls with friends',
              trailing: const Icon(Icons.share, size: 16),
              onTap: () => _shareApp(),
            ),
            _buildDivider(),
            _buildListTile(
              title: 'About',
              subtitle: 'Version 1.1.1',
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () => _showAboutDialog(),
            ),
            _buildDivider(),
            _buildListTile(
              title: 'Privacy Policy',
              subtitle: 'Read our privacy policy',
              trailing: const Icon(Icons.open_in_new, size: 16),
              onTap: () => _openPrivacyPolicy(),
            ),
            _buildDivider(),
          ]),
        ],
      ),
    );
  }

  Widget _buildAppInfoCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Colors.pinkAccent, Colors.purpleAccent],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 30,
            backgroundColor: Colors.white.withValues(alpha: 0.2),
            child: const Icon(Icons.palette, size: 30, color: Colors.white),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'MoodCanvas:Walls',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Wallpaper Creator v1.1.1',
                  style: TextStyle(
                    color: Colors.white.withValues(alpha: 0.8),
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
          IconButton(
            onPressed: () => _showAboutDialog(),
            icon: const Icon(Icons.info_outline, color: Colors.white),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(left: 16, bottom: 8),
      child: Text(
        title,
        style: TextStyle(
          color: Colors.grey[400],
          fontSize: 14,
          fontWeight: FontWeight.w600,
          letterSpacing: 0.5,
        ),
      ),
    );
  }

  Widget _buildSettingsCard(List<Widget> children) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(children: children),
    );
  }

  Widget _buildSwitchTile({
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return SwitchListTile(
      title: Text(
        title,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ),
      subtitle: Text(
        subtitle,
        style: TextStyle(color: Colors.grey[400], fontSize: 14),
      ),
      value: value,
      onChanged: onChanged,
      activeThumbColor: Colors.pinkAccent,
    );
  }

  Widget _buildListTile({
    required String title,
    required String subtitle,
    required Widget trailing,
    required VoidCallback onTap,
  }) {
    return ListTile(
      title: Text(
        title,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ),
      subtitle: Text(
        subtitle,
        style: TextStyle(color: Colors.grey[400], fontSize: 14),
      ),
      trailing: trailing,
      onTap: onTap,
    );
  }

  Widget _buildSliderTile({
    required String title,
    required String subtitle,
    required double value,
    required ValueChanged<double> onChanged,
  }) {
    return ListTile(
      title: Text(
        title,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ),
      subtitle: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            subtitle,
            style: TextStyle(color: Colors.grey[400], fontSize: 14),
          ),
          Slider(
            value: value,
            onChanged: onChanged,
            activeColor: Colors.pinkAccent,
            inactiveColor: Colors.grey[600],
          ),
        ],
      ),
    );
  }

  Widget _buildDivider() {
    return Divider(
      height: 1,
      color: Colors.grey[700],
      indent: 16,
      endIndent: 16,
    );
  }

  void _showAboutDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.grey[800],
        title: const Text(
          'About MoodCanvas:Walls',
          style: TextStyle(color: Colors.white),
        ),
        content: const Text(
          'MoodCanvas:Walls v1.1.1\n\nCreate beautiful, mood-based wallpapers with our powerful editor and stay updated with real-time weather information. Express your creativity and personalize your device.',
          style: TextStyle(color: Colors.white),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('OK', style: TextStyle(color: Colors.pinkAccent)),
          ),
        ],
      ),
    );
  }

  // Share app functionality
  Future<void> _shareApp() async {
    try {
      await SharePlus.instance.share(
        ShareParams(
          text:
              'Check out MoodCanvas:Walls! 🎨\n\nCreate beautiful, mood-based wallpapers with powerful editing tools and stay updated with real-time weather information. Express your creativity and personalize your device!\n\nDownload now: https://moodcanvas.app',
          subject: 'MoodCanvas:Walls - Wallpaper Creator',
        ),
      );
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('Failed to share app: $e');
      }
    }
  }

  // Open privacy policy URL
  Future<void> _openPrivacyPolicy() async {
    final Uri url = Uri.parse('https://moodcanvas.bitbucket.io/privacy.html');
    try {
      if (await canLaunchUrl(url)) {
        await launchUrl(url, mode: LaunchMode.externalApplication);
      } else {
        if (mounted) {
          _showErrorSnackBar('Could not open privacy policy');
        }
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('Failed to open privacy policy: $e');
      }
    }
  }

  // Open terms of service URL
  Future<void> _openTermsOfService() async {
    final Uri url = Uri.parse('https://moodcanvas.bitbucket.io/terms.html');
    try {
      if (await canLaunchUrl(url)) {
        await launchUrl(url, mode: LaunchMode.externalApplication);
      } else {
        if (mounted) {
          _showErrorSnackBar('Could not open terms of service');
        }
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('Failed to open terms of service: $e');
      }
    }
  }

  // Show error snackbar
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        duration: const Duration(seconds: 3),
      ),
    );
  }
}
