import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hum/core/constants/app_text.dart';
import 'package:hum/core/constants/app_theme.dart';
import 'package:hum/core/utils/toaster.dart';
import 'package:hum/services/firebase_auth.dart';
import 'package:hum/widgets/widget_buttons.dart';
import 'package:hum/widgets/widget_text_fields.dart';

class AuthView extends StatefulWidget {
  const AuthView({super.key});
  @override
  State<AuthView> createState() => _AuthViewState();
}

class _AuthViewState extends State<AuthView> {
  bool signUp = false;
  bool workingOnSignIn = false;

  final ctrlEmail = TextEditingController();
  final ctrlPassword = TextEditingController();
  final ctrlUsername = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final bottomInset = MediaQuery.of(context).viewInsets.bottom; // keyboard

    return CupertinoPageScaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: CupertinoDynamicColor.resolve(colorBarBackground, context),
      navigationBar: const CupertinoNavigationBar(),
      child: SafeArea(
        bottom: false, // we'll add our own bottom padding that follows the keyboard
        child: LayoutBuilder(
          builder: (context, constraints) {
            return SingleChildScrollView(
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
              physics: const BouncingScrollPhysics(),
              padding: EdgeInsets.fromLTRB(14, 0, 14, bottomInset + 16),
              child: ConstrainedBox(
                constraints: BoxConstraints(minHeight: constraints.maxHeight),
                child: Center(
                  // centers when there's room; scrolls when not
                  child: Column(
                    spacing: 8,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const SizedBox(height: 30),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 16.0),
                        child: Text(
                          signUp ? authTitleSignUp : authTitleSignIn,
                          style: const TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
                          textAlign: TextAlign.center,
                        ),
                      ),

                      if (signUp)
                        TXTFieldInput(
                          controller: ctrlUsername,
                          placeholder: authPlaceholderDisplayName,
                          inputType: TextInputType.name,
                        ),

                      TXTFieldInput(
                        controller: ctrlEmail,
                        placeholder: authPlaceholderEmail,
                        inputType: TextInputType.emailAddress,
                        password: false,
                      ),

                      TXTFieldInput(
                        controller: ctrlPassword,
                        placeholder: authPlaceholderPassword,
                        inputType: TextInputType.text,
                        password: true,
                      ),

                      // Sign in/up
                      Column(
                        children: [
                          BTNFilledAnimated(
                            working: workingOnSignIn,
                            text: signUp ? authSignUp : authSignIn,
                            color: CupertinoDynamicColor.resolve(colorAccentSecondary, context),
                            action: () async {
                              final ctx = context;
                              try {
                                if (!mounted) return;
                                setState(() => workingOnSignIn = true);
                                if (signUp) {
                                  await signUpEmail(
                                    email: ctrlEmail.text,
                                    password: ctrlPassword.text,
                                  );
                                } else {
                                  await signInEmail(
                                    email: ctrlEmail.text,
                                    password: ctrlPassword.text,
                                  );
                                }
                                if (!mounted) return;
                                setState(() => workingOnSignIn = false);
                              } catch (e) {
                                if (!mounted) return;
                                setState(() => workingOnSignIn = false);
                                if (ctx.mounted) {
                                  showCupertinoToast(ctx, e.toString());
                                }
                              }
                            },
                          ),
                          BTNText(
                            text: signUp ? authModeSignIn : authModeSignUp,
                            action: () => setState(() => signUp = !signUp),
                          ),
                        ],
                      ),

                      const Divider(),

                      // Providers
                      Column(
                        children: [
                          SizedBox(
                            width: double.infinity,
                            child: CupertinoButton(
                              color: CupertinoColors.white,
                              borderRadius: BorderRadius.circular(roundLarge),
                              padding: const EdgeInsets.symmetric(vertical: 14),
                              onPressed: () async {
                                final ctx = context;
                                try {
                                  await signInWithGoogle();
                                } catch (e) {
                                  if (ctx.mounted) showCupertinoToast(ctx, e.toString());
                                }
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: const [
                                  Icon(Icons.g_mobiledata, color: CupertinoColors.black, size: 28),
                                  SizedBox(width: 8),
                                  Text(
                                    authSignGoogle,
                                    style: TextStyle(
                                      color: CupertinoColors.black,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          const SizedBox(height: 12),
                          SizedBox(
                            width: double.infinity,
                            child: CupertinoButton(
                              color: CupertinoColors.black,
                              borderRadius: BorderRadius.circular(roundLarge),
                              padding: const EdgeInsets.symmetric(vertical: 14),
                              onPressed: () {},
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: const [
                                  Text(
                                    '',
                                    style: TextStyle(fontSize: 22, color: CupertinoColors.white),
                                  ),
                                  SizedBox(width: 8),
                                  Text(
                                    authSignApple,
                                    style: TextStyle(
                                      color: CupertinoColors.white,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
