import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/config/features.dart';
import 'package:kasy_kit/core/data/models/user.dart';
import 'package:kasy_kit/core/haptics/haptic_feedback_notifier.dart';
import 'package:kasy_kit/core/security/biometric_preference_notifier.dart';
import 'package:kasy_kit/core/security/biometric_service.dart';
import 'package:kasy_kit/core/security/biometric_ui_bundle.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/admin_bottom_sheet.dart';
import 'package:kasy_kit/features/settings/ui/components/avatar_component.dart';
import 'package:kasy_kit/features/settings/ui/components/delete_user_component.dart';
import 'package:kasy_kit/features/settings/ui/components/language_switcher.dart';
import 'package:kasy_kit/features/settings/ui/widgets/settings_tile.dart';
import 'package:kasy_kit/i18n/translations.g.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tr = context.t.settings;
    final user = ref.watch(userStateNotifierProvider).user;
    final isAuthenticated = user is AuthenticatedUserData;
    final (displayName, displayEmail) = switch (user) {
      final AuthenticatedUserData u => (
        (u.name?.isNotEmpty ?? false) ? u.name! : u.email.split('@').first,
        u.email,
      ),
      _ => (tr.my_account, ''),
    };

    return KasyOverlayScaffold(
      title: tr.title,
      appBarStyle: KasyAppBarStyle.rootTab,
      trailing: Builder(
        builder: (ctx) => KasyChromeOrbIconButton(
          icon: KasyIcons.logout,
          iconSize: 20,
          foregroundColor: ctx.colors.error,
          onPressed: () => showKasyConfirmDialog(
            ctx,
            title: tr.disconnect_confirm_title,
            message: tr.disconnect_confirm_message,
            cancelLabel: tr.disconnect_cancel,
            confirmLabel: tr.disconnect,
            onConfirm: () =>
                ref.read(userStateNotifierProvider.notifier).onLogout(),
          ),
        ),
      ),
      slivers: [
        SliverList.list(
          children: [
            ProfileTile(
              title: displayName,
              subtitle: displayEmail,
              isAuthenticated: isAuthenticated,
              onTap: isAuthenticated ? null : () => context.push('/signup'),
            ),
            const SizedBox(height: KasySpacing.xl),
            _SectionLabel(tr.section_preferences_label),
            const SizedBox(height: KasySpacing.xs),
            SettingsContainer(
              child: Wrap(
                children: [
                  const ThemeSwitcher(),
                  const SettingsDivider(),
                  const HapticFeedbackSwitcher(),
                  const SettingsDivider(),
                  const LanguageSwitcher(),
                  if (withLocalNotifications) ...[
                    const SettingsDivider(),
                    SettingsTile(
                      icon: KasyIcons.notification,
                      title: tr.reminders,
                      onTap: () => context.push('/reminder'),
                    ),
                  ],
                  if (withFeedback) ...[
                    const SettingsDivider(),
                    SettingsTile(
                      icon: KasyIcons.message,
                      title: tr.feedback,
                      onTap: () => context.push('/feedback'),
                    ),
                  ],
                  if (withRevenuecat) ...[
                    const SettingsDivider(),
                    SettingsTile(
                      icon: KasyIcons.payment,
                      title: tr.premium,
                      onTap: () => context.push('/premium'),
                    ),
                  ],
                ],
              ),
            ),
            if (isAuthenticated && !kIsWeb) ...[
              const SizedBox(height: KasySpacing.xl),
              _SectionLabel(tr.section_security_label),
              const SizedBox(height: KasySpacing.xs),
              const SettingsContainer(
                child: BiometricSwitcher(),
              ),
            ],
            const SizedBox(height: KasySpacing.xl),
            _SectionLabel(tr.section_support_label),
            const SizedBox(height: KasySpacing.xs),
            SettingsContainer(
              child: Wrap(
                children: [
                  SettingsTile(
                    icon: KasyIcons.privacy,
                    title: tr.privacy,
                    onTap: () => launchUrl(Uri.parse('https://kasy.dev/privacy/')),
                  ),
                  const SettingsDivider(),
                  SettingsTile(
                    icon: KasyIcons.help,
                    title: tr.support,
                    onTap: () => launchUrl(Uri.parse('https://kasy.dev/')),
                  ),
                ],
              ),
            ),
            const SizedBox(height: KasySpacing.xxl),
            const DeleteUserButton(),
            const SizedBox(height: KasySpacing.xl),
            const _VersionLabel(),
            const SizedBox(height: KasySpacing.xl),
          ],
        ),
      ],
    );
  }
}

class _SectionLabel extends StatelessWidget {
  final String label;
  const _SectionLabel(this.label);

  @override
  Widget build(BuildContext context) {
    return Text(
      label,
      style: context.textTheme.labelMedium?.copyWith(
        fontSize: 13,
        color: context.colors.muted,
        letterSpacing: 1.2,
        fontWeight: FontWeight.w600,
      ),
    );
  }
}

class SettingsContainer extends StatelessWidget {
  final Widget child;

  const SettingsContainer({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(
        vertical: KasySpacing.smd,
        horizontal: KasySpacing.md,
      ),
      decoration: BoxDecoration(
        borderRadius: KasyRadius.smBorderRadius,
        color: context.colors.surface,
      ),
      child: child,
    );
  }
}

class ProfileTile extends StatelessWidget {
  final String title;
  final String subtitle;
  final bool isAuthenticated;
  final VoidCallback? onTap;

  const ProfileTile({
    super.key,
    required this.title,
    required this.subtitle,
    required this.isAuthenticated,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final Widget content = Padding(
      padding: const EdgeInsets.symmetric(
        vertical: KasySpacing.smd,
        horizontal: KasySpacing.md,
      ),
      child: Row(
        children: [
          const EditableUserAvatar(
            diameter: 70,
          ),
          const SizedBox(width: KasySpacing.sm),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  title,
                  textHeightBehavior: const TextHeightBehavior(
                    applyHeightToFirstAscent: false,
                    applyHeightToLastDescent: false,
                  ),
                  style: context.textTheme.titleMedium!.copyWith(
                    color: context.colors.onSurface,
                    fontWeight: FontWeight.w600,
                    height: 1.12,
                  ),
                ),
                if (subtitle.isNotEmpty) ...[
                  Text(
                    subtitle,
                    textHeightBehavior: const TextHeightBehavior(
                      applyHeightToFirstAscent: false,
                      applyHeightToLastDescent: false,
                    ),
                    style: context.textTheme.bodySmall!.copyWith(
                      color: context.colors.muted,
                      height: 1.15,
                    ),
                  ),
                ],
                if (!isAuthenticated) ...[
                  Text(
                    context.t.settings.register,
                    textHeightBehavior: const TextHeightBehavior(
                      applyHeightToFirstAscent: false,
                      applyHeightToLastDescent: false,
                    ),
                    style: context.textTheme.bodyLarge!.copyWith(
                      color: context.colors.muted,
                      fontWeight: FontWeight.w500,
                      height: 1.15,
                    ),
                  ),
                ],
              ],
            ),
          ),
          if (onTap != null) const SettingsListChevron(),
        ],
      ),
    );

    return Container(
      decoration: BoxDecoration(
        borderRadius: KasyRadius.smBorderRadius,
        color: context.colors.surface,
      ),
      child: ClipRRect(
        borderRadius: KasyRadius.smBorderRadius,
        child: onTap != null
            ? InkWell(onTap: onTap, child: content)
            : content,
      ),
    );
  }
}

class _VersionLabel extends StatefulWidget {
  const _VersionLabel();

  @override
  State<_VersionLabel> createState() => _VersionLabelState();
}

class _VersionLabelState extends State<_VersionLabel> {
  String _version = '';

  @override
  void initState() {
    super.initState();
    PackageInfo.fromPlatform().then((info) {
      if (mounted) setState(() => _version = 'v${info.version}');
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onDoubleTap: () => showAdminBottomSheet(context),
      child: Center(
        child: Text(
          _version,
          style: context.textTheme.bodySmall?.copyWith(
            color: context.colors.onSurface.withValues(alpha: 0.3),
          ),
        ),
      ),
    );
  }
}

class BiometricSwitcher extends ConsumerWidget {
  const BiometricSwitcher({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isEnabled = ref.watch(biometricPreferenceProvider);
    final tr = context.t.settings;
    final platform = Theme.of(context).platform;
    final slotAsync = ref.watch(biometricCopySlotFamily(platform));
    final subtitle = slotAsync.when(
      data: (slot) => BioBundle.fromSlot(context, slot).settingsSubtitle,
      loading: () =>
          BioBundle.fallbackForPlatform(context).settingsSubtitle,
      error: (_, _) =>
          BioBundle.fallbackForPlatform(context).settingsSubtitle,
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SettingsSwitchTile(
          icon: KasyIcons.fingerprint,
          title: tr.biometric_title,
          value: isEnabled,
          onChanged: (value) => _onChanged(context, ref, value),
        ),
        Padding(
          padding: const EdgeInsets.only(
            left: 21 + KasySpacing.sm,
            bottom: KasySpacing.xs,
          ),
          child: Text(
            subtitle,
            style: context.textTheme.bodySmall?.copyWith(
              color: context.colors.muted,
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _onChanged(
    BuildContext context,
    WidgetRef ref,
    bool value,
  ) async {
    if (!value) {
      _confirmDisable(context, ref);
      return;
    }
    await _enableBiometric(context, ref);
  }

  Future<void> _enableBiometric(BuildContext context, WidgetRef ref) async {
    final tr = context.t.settings;
    final platform = Theme.of(context).platform;
    final slot = await ref.read(biometricCopySlotFamily(platform).future);
    if (!context.mounted) return;
    final bundle = BioBundle.fromSlot(context, slot);
    final unavailableMsg = bundle.unavailableMessage;
    final reason = bundle.enableReason;

    final service = ref.read(biometricServiceProvider);
    final isAvailable = await service.isAvailable();
    if (!isAvailable) {
      if (!context.mounted) return;
      showKasyToast(
        context,
        title: unavailableMsg,
        tone: KasyToastTone.warning,
      );
      return;
    }
    final authenticated = await service.authenticate(localizedReason: reason);
    if (!context.mounted) return;
    if (!authenticated) {
      showKasyToast(
        context,
        title: tr.biometric_not_enabled_message,
        tone: KasyToastTone.warning,
      );
      return;
    }
    await ref.read(biometricPreferenceProvider.notifier).setEnabled(true);
  }

  void _confirmDisable(BuildContext context, WidgetRef ref) {
    final tr = context.t.settings;
    showKasyConfirmDialog(
      context,
      title: tr.biometric_disable_title,
      message: tr.biometric_disable_message,
      cancelLabel: tr.biometric_disable_cancel,
      confirmLabel: tr.biometric_disable_confirm,
      onConfirm: () {
        ref.read(biometricPreferenceProvider.notifier).setEnabled(false);
      },
    );
  }
}

class HapticFeedbackSwitcher extends ConsumerWidget {
  const HapticFeedbackSwitcher({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isEnabled = ref.watch(hapticFeedbackProvider);
    return SettingsSwitchTile(
      icon: KasyIcons.phoneAndroid,
      title: context.t.settings.haptic_feedback_title,
      value: isEnabled,
      onChanged: (_) => ref.read(hapticFeedbackProvider.notifier).toggle(),
    );
  }
}

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

  IconData _iconFor(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.system:
        return KasyIcons.phoneAndroid;
      case ThemeMode.dark:
        return KasyIcons.darkMode;
      case ThemeMode.light:
        return KasyIcons.lightMode;
    }
  }

  @override
  Widget build(BuildContext context) {
    final tr = context.t.settings;
    final theme = ThemeProvider.of(context);
    final options = <({ThemeMode mode, IconData icon, String label})>[
      (
        mode: ThemeMode.system,
        icon: KasyIcons.phoneAndroid,
        label: tr.theme_option_system,
      ),
      (
        mode: ThemeMode.light,
        icon: KasyIcons.lightMode,
        label: tr.theme_option_light,
      ),
      (
        mode: ThemeMode.dark,
        icon: KasyIcons.darkMode,
        label: tr.theme_option_dark,
      ),
    ];
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: KasySpacing.sm),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Icon(
                _iconFor(theme.mode),
                size: 21,
                color: context.colors.onSurface,
              ),
              const SizedBox(width: KasySpacing.sm),
              Expanded(
                child: Text(
                  tr.theme_title,
                  style: context.textTheme.titleMedium?.copyWith(
                    color: context.colors.onSurface,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: KasySpacing.sm),
          _ThemeModeSegmented(
            current: theme.mode,
            options: options,
            onChanged: theme.setMode,
          ),
        ],
      ),
    );
  }
}

class _ThemeModeSegmented extends StatelessWidget {
  const _ThemeModeSegmented({
    required this.current,
    required this.options,
    required this.onChanged,
  });

  final ThemeMode current;
  final List<({ThemeMode mode, IconData icon, String label})> options;
  final ValueChanged<ThemeMode> onChanged;

  @override
  Widget build(BuildContext context) {
    final trackColor = context.colors.onSurface.withValues(alpha: 0.06);
    return Container(
      padding: const EdgeInsets.all(3),
      decoration: BoxDecoration(
        color: trackColor,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          for (final opt in options)
            Expanded(
              child: _ThemeModeSegment(
                icon: opt.icon,
                label: opt.label,
                selected: current == opt.mode,
                onTap: () => onChanged(opt.mode),
              ),
            ),
        ],
      ),
    );
  }
}

class _ThemeModeSegment extends StatelessWidget {
  const _ThemeModeSegment({
    required this.icon,
    required this.label,
    required this.selected,
    required this.onTap,
  });

  final IconData icon;
  final String label;
  final bool selected;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final selectedBg = context.colors.surface;
    final selectedFg = context.colors.onSurface;
    final unselectedFg = context.colors.muted;
    return Semantics(
      button: true,
      selected: selected,
      label: label,
      child: GestureDetector(
        onTap: onTap,
        behavior: HitTestBehavior.opaque,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 160),
          curve: Curves.easeOut,
          padding: const EdgeInsets.symmetric(vertical: 8),
          decoration: BoxDecoration(
            color: selected ? selectedBg : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
            boxShadow: selected
                ? [
                    BoxShadow(
                      color: Colors.black.withValues(alpha: 0.06),
                      blurRadius: 4,
                      offset: const Offset(0, 1),
                    ),
                  ]
                : const [],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                icon,
                size: 18,
                color: selected ? selectedFg : unselectedFg,
              ),
              const SizedBox(height: 2),
              Text(
                label,
                style: context.textTheme.labelSmall?.copyWith(
                  color: selected ? selectedFg : unselectedFg,
                  fontWeight: selected ? FontWeight.w600 : FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
