import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../constants/font_constants.dart';
import '../../widgets/text_widget.dart';

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

  @override
  State<NotificationSettingsView> createState() =>
      _NotificationSettingsViewState();
}

class _NotificationSettingsViewState extends State<NotificationSettingsView>
    with SingleTickerProviderStateMixin {
  bool notificationsEnabled = true;
  bool soundEnabled = true;
  bool vibrationEnabled = true;

  static const Color primaryColor = Color(0xFF662582);

  late AnimationController _controller;
  late Animation<double> _fadeAnim;
  late Animation<double> _scaleAnim;

  @override
  void initState() {
    super.initState();
    _loadSettings();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );

    _fadeAnim = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    );

    _scaleAnim = Tween<double>(begin: 0.95, end: 1).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeOutBack),
    );

    _controller.forward();
  }

  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      notificationsEnabled = prefs.getBool('notificationsEnabled') ?? true;
      soundEnabled = prefs.getBool('notificationSound') ?? true;
      vibrationEnabled = prefs.getBool('notificationVibration') ?? true;
    });
  }

  Future<void> _saveSetting(String key, bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(key, value);
  }

  Widget _animatedSettingCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return AnimatedScale(
      duration: const Duration(milliseconds: 250),
      scale: value ? 1 : 0.98,
      child: Container(
        margin: const EdgeInsets.only(bottom: 10),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.06),
              blurRadius: 12,
              offset: const Offset(0, 6),
            ),
          ],
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    primaryColor,
                    primaryColor.withOpacity(0.7),
                  ],
                ),
                shape: BoxShape.circle,
              ),
              child: Icon(icon, color: Colors.white, size: 20),
            ),
            const SizedBox(width: 14),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ReusableTextWidget(
                    text: title,
                    fontSize: 14,
                    fontWeight: FontWeight.w800,
                    fontFamily: FontConstants.fontFamily,
                    color: Colors.black.withOpacity(0.65),
                  ),
                  const SizedBox(height: 4),
                  ReusableTextWidget(
                    text: subtitle,
                    fontSize: 12,
                    fontWeight: FontWeight.w700,
                    fontFamily: FontConstants.fontFamily,
                    color: Colors.grey[500],
                  ),
                ],
              ),
            ),
            Switch.adaptive(
              value: value,
              activeColor: primaryColor,
              onChanged: onChanged,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      // 🔹 Status bar like Account page
      value: const SystemUiOverlayStyle(
        statusBarColor: Colors.white,           // white background
        statusBarIconBrightness: Brightness.dark, // dark icons
        statusBarBrightness: Brightness.light,    // iOS
      ),
      child: Scaffold(
        backgroundColor: const Color(0xFFF6F6F6),
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          title: ReusableTextWidget(
            text: "Notifications",
            fontSize: 20,
            fontWeight: FontWeight.w600,
            fontFamily: FontConstants.fontFamily,
            color: Colors.black,
          ),
          iconTheme: const IconThemeData(color: Colors.black),
        ),
        body: FadeTransition(
          opacity: _fadeAnim,
          child: ScaleTransition(
            scale: _scaleAnim,
            child: ListView(
              padding: const EdgeInsets.all(12),
              children: [
                /// 🔔 Animated Header
                Container(
                  padding: const EdgeInsets.all(20),
                  margin: const EdgeInsets.only(bottom: 24),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(18),
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        primaryColor,
                        primaryColor.withOpacity(0.85),
                      ],
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: primaryColor.withOpacity(0.35),
                        blurRadius: 4,
                        offset: const Offset(1, 1),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.notifications_active,
                          color: Colors.white, size: 30),
                      const SizedBox(width: 16),
                      Expanded(
                        child: ReusableTextWidget(
                          text:
                          "Control alerts, audio and vibrations\nfor Nearle Daily notifications",
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          fontFamily: FontConstants.fontFamily,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),

                /// 🔕 MASTER SWITCH
                _animatedSettingCard(
                  icon: Icons.notifications_off_outlined,
                  title: "Enable Notifications",
                  subtitle: "Turn all notifications on or off",
                  value: notificationsEnabled,
                  onChanged: (val) async {
                    setState(() => notificationsEnabled = val);
                    await _saveSetting('notificationsEnabled', val);
                  },
                ),

                /// 🔊 SUB SETTINGS
                IgnorePointer(
                  ignoring: !notificationsEnabled,
                  child: AnimatedOpacity(
                    duration: const Duration(milliseconds: 300),
                    opacity: notificationsEnabled ? 1 : 0.4,
                    child: Column(
                      children: [
                        _animatedSettingCard(
                          icon: Icons.volume_up_outlined,
                          title: "Notification Sound",
                          subtitle: "Play sound for notifications",
                          value: soundEnabled,
                          onChanged: (val) async {
                            setState(() => soundEnabled = val);
                            await _saveSetting('notificationSound', val);
                          },
                        ),
                        _animatedSettingCard(
                          icon: Icons.vibration,
                          title: "Vibration",
                          subtitle: "Vibrate on notification",
                          value: vibrationEnabled,
                          onChanged: (val) async {
                            setState(() => vibrationEnabled = val);
                            await _saveSetting(
                                'notificationVibration', val);
                          },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

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