import 'dart:convert';

import 'package:auth/src/features/login/presentation/widgets/two_factor_bottom_sheet.dart';
import 'package:auth/src/features/sign_up/presentation/state/sign_up_view_model.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:navigation/navigation.dart';
import 'package:sf_localizations/sf_localizations.dart';

class SecretCodeScreen extends ConsumerWidget {
  final NavigationContract navigationContract;

  const SecretCodeScreen({super.key, required this.navigationContract});

  Uint8List? _qrBytes(String? dataUri) {
    final value = (dataUri ?? '').trim();
    if (value.isEmpty) return null;

    final idx = value.indexOf('base64,');
    final b64 = idx == -1 ? value : value.substring(idx + 7);

    try {
      return base64Decode(b64);
    } catch (_) {
      return null;
    }
  }

  Future<bool?> _openTwoFactorSignUpBottomSheet(
    BuildContext context,
    WidgetRef ref,
  ) async {
    final token = ref.read(signUpViewModelProvider).token;
    if (token.trim().isEmpty) return false;

    return showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      isDismissible: false,
      enableDrag: false,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Consumer(
          builder: (context, ref, _) {
            final theme = ref.watch(themePortProvider);
            final vm = ref.read(signUpViewModelProvider.notifier);

            final otpErrorKey = ref.watch(
              signUpViewModelProvider.select((s) => s.otpError),
            );
            final isOtpLoading = ref.watch(
              signUpViewModelProvider.select((s) => s.isOtpLoading),
            );
            final otpCode = ref.watch(
              signUpViewModelProvider.select((s) => s.otpCode),
            );

            final otpErrorText = otpErrorKey.isEmpty
                ? ''
                : context.translate(otpErrorKey);

            Future<void> onVerify() async {
              FocusManager.instance.primaryFocus?.unfocus();

              final ok = await vm.verifyTwoFACodeSignUp(token: token);
              if (!context.mounted) return;

              if (ok) Navigator.of(context).pop(true);
            }

            return TwoFactorBottomSheetView(
              theme: theme,
              title: context.translate(I18n.twoFactorTitle),
              subtitle: context.translate(I18n.twoFactorSubtitle),
              verifyText: context.translate(I18n.twoFactorVerify),
              closeText: context.translate(I18n.close),
              isOtpLoading: isOtpLoading,
              otpCode: otpCode,
              otpErrorText: otpErrorText,
              onChanged: vm.setOtpCode,
              onVerify: onVerify,
              onClose: () => Navigator.of(context).pop(false),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = ref.watch(themePortProvider);
    final vm = ref.read(signUpViewModelProvider.notifier);
    final state = ref.watch(signUpViewModelProvider);

    final secret = state.twoFASecret?.item.secret.trim() ?? '';
    final qrDataUri = state.twoFASecret?.item.qr;
    final qrBytes = _qrBytes(qrDataUri);

    return Scaffold(
      backgroundColor: theme.getColorFor(ThemeCode.backgroundPrimary),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.fromLTRB(24, 8, 24, 24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                context.translate(I18n.secretCodeTitle),
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w700,
                  color: theme.getColorFor(ThemeCode.textPrimary),
                ),
              ),
              const SizedBox(height: 20),

              _StepBlock(
                theme: theme,
                number: '1.',
                title: context.translate(I18n.secretCodeStep1Title),
                body: context.translate(I18n.secretCodeStep1Body),
              ),
              const SizedBox(height: 14),

              _StepBlock(
                theme: theme,
                number: '2.',
                title: context.translate(I18n.secretCodeStep2Title),
                body: context.translate(I18n.secretCodeStep2Body),
              ),
              const SizedBox(height: 12),

              Center(
                child: Container(
                  width: 150,
                  height: 150,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(width: 1, color: Colors.black),
                    color: theme.getColorFor(ThemeCode.backgroundSecondary),
                  ),
                  child: qrBytes == null
                      ? const Center(child: Icon(Icons.qr_code_2, size: 60))
                      : ClipRRect(
                          borderRadius: BorderRadius.circular(12),
                          child: Image.memory(qrBytes, fit: BoxFit.cover),
                        ),
                ),
              ),
              const SizedBox(height: 12),

              Center(
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 14,
                    vertical: 10,
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: theme.getColorFor(ThemeCode.backgroundSecondary),
                    border: Border.all(width: 1, color: Colors.black),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        secret,
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          letterSpacing: 1.1,
                          color: theme.getColorFor(ThemeCode.textPrimary),
                        ),
                      ),
                      const SizedBox(width: 10),
                      IconButton(
                        visualDensity: VisualDensity.compact,
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                        icon: const Icon(Icons.copy, size: 18),
                        onPressed: secret.isEmpty
                            ? null
                            : () async {
                                await Clipboard.setData(
                                  ClipboardData(text: secret),
                                );
                                if (!context.mounted) return;
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: Text(
                                      context.translate(
                                        I18n.secretCodeKeyCopied,
                                      ),
                                    ),
                                  ),
                                );
                              },
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 18),
              _StepBlock(
                theme: theme,
                number: '3.',
                title: context.translate(I18n.secretCodeStep3Title),
                body: context.translate(I18n.secretCodeStep3Body),
              ),

              const SizedBox(height: 26),
              PrimaryButton(
                onPressed: () async {
                  final verified = await _openTwoFactorSignUpBottomSheet(
                    context,
                    ref,
                  );
                  if (!context.mounted) return;

                  if (verified == true) {
                    vm.showAccountCreated();
                  }
                },
                text: context.translate(I18n.secretCodeConfigure),
                color: Color.fromRGBO(88, 142, 165, 1),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _StepBlock extends StatelessWidget {
  final ThemePort theme;
  final String number;
  final String title;
  final String body;

  const _StepBlock({
    required this.theme,
    required this.number,
    required this.title,
    required this.body,
  });

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        style: TextStyle(
          height: 1.35,
          fontSize: 14,
          color: theme.getColorFor(ThemeCode.textPrimary),
        ),
        children: [
          TextSpan(
            text: '$number ',
            style: const TextStyle(fontWeight: FontWeight.w700),
          ),
          TextSpan(
            text: '$title\n',
            style: const TextStyle(fontWeight: FontWeight.w700),
          ),
          TextSpan(
            text: body,
            style: TextStyle(
              fontWeight: FontWeight.w400,
              color: theme.getColorFor(ThemeCode.textSecondary),
            ),
          ),
        ],
      ),
    );
  }
}
