import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../../../../core/theme/app_colors.dart';
import '../../../../core/theme/app_text_styles.dart';
import '../../../../core/theme/app_spacing.dart';
import '../../../../core/theme/app_gradients.dart';
import '../../../../core/utils/validators.dart';
import '../../../../core/widgets/fs_button.dart';
import '../../../../core/widgets/fs_text_field.dart';
import '../bloc/auth_cubit.dart';
import '../bloc/auth_state.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailCtrl = TextEditingController();
  final _passwordCtrl = TextEditingController();
  bool _obscurePassword = true;

  @override
  void dispose() {
    _emailCtrl.dispose();
    _passwordCtrl.dispose();
    super.dispose();
  }

  void _submit() {
    if (!_formKey.currentState!.validate()) return;
    context.read<AuthCubit>().login(
          _emailCtrl.text.trim(),
          _passwordCtrl.text,
        );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 28),
            child: BlocListener<AuthCubit, AuthState>(
              listener: (context, state) {
                // Navigation is handled by GoRouter redirect — no need here
              },
              child: Form(
                key: _formKey,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // ── Logo ──
                    const Text('📊', style: TextStyle(fontSize: 48)),
                    const SizedBox(height: 12),
                    ShaderMask(
                      shaderCallback: (b) =>
                          AppGradients.textAccent.createShader(b),
                      child: Text(
                        'FinSim',
                        style: AppTextStyles.headlineLarge
                            .copyWith(color: Colors.white),
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Investment Scenario Engine',
                      style: AppTextStyles.bodySmall
                          .copyWith(color: AppColors.textTertiary),
                    ),
                    const SizedBox(height: 36),

                    // ── Error Banner ──
                    BlocBuilder<AuthCubit, AuthState>(
                      buildWhen: (prev, curr) =>
                          curr is AuthError || prev is AuthError,
                      builder: (context, state) {
                        if (state is! AuthError) {
                          return const SizedBox.shrink();
                        }
                        return Container(
                          width: double.infinity,
                          margin: const EdgeInsets.only(bottom: 16),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 14, vertical: 10),
                          decoration: BoxDecoration(
                            color: AppColors.errorBg,
                            border: Border.all(
                                color: AppColors.error.withOpacity(0.25)),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            state.message,
                            style: AppTextStyles.bodySmall
                                .copyWith(color: AppColors.errorLight),
                          ),
                        );
                      },
                    ),

                    // ── Fields ──
                    FSTextField(
                      label: 'Email',
                      hint: 'your@email.com',
                      controller: _emailCtrl,
                      validator: Validators.email,
                      keyboardType: TextInputType.emailAddress,
                      textInputAction: TextInputAction.next,
                    ),
                    AppSpacing.vMd,
                    FSTextField(
                      label: 'Password',
                      hint: '••••••••',
                      controller: _passwordCtrl,
                      validator: Validators.password,
                      obscureText: _obscurePassword,
                      textInputAction: TextInputAction.done,
                      onEditingComplete: _submit,
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscurePassword
                              ? Icons.visibility_off_outlined
                              : Icons.visibility_outlined,
                          color: AppColors.textTertiary,
                          size: 20,
                        ),
                        onPressed: () =>
                            setState(() => _obscurePassword = !_obscurePassword),
                      ),
                    ),
                    AppSpacing.vLg,

                    // ── Submit ──
                    BlocBuilder<AuthCubit, AuthState>(
                      builder: (context, state) {
                        return FSButton(
                          label: 'Sign In',
                          isLoading: state is AuthLoading,
                          onPressed: state is AuthLoading ? null : _submit,
                        );
                      },
                    ),
                    AppSpacing.vLg,

                    // ── Toggle ──
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          "Don't have an account? ",
                          style: AppTextStyles.bodySmall,
                        ),
                        GestureDetector(
                          onTap: () => context.go('/register'),
                          child: Text(
                            'Create one',
                            style: AppTextStyles.bodySmall.copyWith(
                              color: AppColors.accentLight,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}