import 'package:country_pickers/country.dart';
import 'package:country_pickers/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:lba/screens/auth/bloc/auth_bloc.dart';
import 'package:lba/screens/auth/user_info_page.dart';
import 'package:lba/widgets/app_snackbar.dart';
import '../../extension/screenSize.dart';
import '../../gen/assets.gen.dart';
import '../../res/colors.dart';
import '../../widgets/custom_country_picker.dart';
import 'otp_verification_page.dart';
import '../../widgets/button.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController countryController = TextEditingController();
  Country _selectedCountry = CountryPickerUtils.getCountryByPhoneCode('971');
  bool keepSignedIn = false;

  @override
  void initState() {
    super.initState();
    countryController.text = _selectedCountry.name;
  }

  @override
  Widget build(BuildContext context) {
    final height = context.screenHeight;

    return Scaffold(
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 48),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Padding(
                  padding: const EdgeInsets.only(top: 50),
                  child: SvgPicture.asset(
                    Assets.images.logo.path,
                    height: height / 5.2,
                  ),
                ),
              ),
              SizedBox(height: height / 25),
              const Text(
                "Login",
                style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: height / 100),
              const Text(
                "Please enter your phone number",
                style: TextStyle(fontSize: 17),
              ),
              const SizedBox(height: 25),

              TextField(
                controller: countryController,
                readOnly: true,
                onTap: () => _openCountryPicker(context),
                decoration: InputDecoration(
                  labelText: "Country",
                  prefixIcon: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 15,
                    ),
                    child: CountryPickerUtils.getDefaultFlagImage(
                      _selectedCountry,
                    ),
                  ),
                  suffixIcon: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: SvgPicture.asset(
                      Assets.icons.arrowDownBlack.path,
                      colorFilter: ColorFilter.mode(
                        AppColors.textPrimary,
                        BlendMode.srcIn,
                      ),
                    ),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: BorderSide(color: AppColors.borderPrimary),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: BorderSide(
                      color: AppColors.borderPrimary,
                      width: 2,
                    ),
                  ),
                ),
              ),

              const SizedBox(height: 16),

              TextField(
                controller: phoneController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: "Phone Number",
                  hintText: "_ _ _ _ _ _ _ _ _ _ _",
                  labelStyle: TextStyle(color: AppColors.textPrimary),
                  prefix: Text(
                    "+${_selectedCountry.phoneCode} ",
                    style: TextStyle(
                      fontSize: 16,
                      color: AppColors.textPrimary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: BorderSide(
                      color: AppColors.borderPrimary,
                      width: 2,
                    ),
                  ),
                ),
              ),

              const SizedBox(height: 25),
              // InkWell(
              //   onTap: () {
              //     setState(() {
              //       keepSignedIn = !keepSignedIn;
              //     });
              //   },
              // child: Row(
              //   mainAxisAlignment: MainAxisAlignment.start,
              //   children: [
              //     Checkbox(
              //       value: keepSignedIn,
              //       activeColor: AppColors.borderPrimary,
              //       onChanged: (bool? value) {
              //         setState(() {
              //           keepSignedIn = value ?? false;
              //         });
              //       },
              //     ),
              //     const Text(
              //       "Keep me signed in",
              //       style: TextStyle(fontSize: 15),
              //     ),
              //   ],
              // ),
              // ),
              SizedBox(height: height / 60),
              BlocConsumer<AuthBloc, AuthState>(
                listener: (context, state) {
                  // اینجا رو تغییر بده
                  if (state is AuthCodeSent) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => OTPVerificationPage(
                              phoneNumber: state.phoneNumber,
                              timeDue:
                                  DateTime.now()
                                      .add(const Duration(minutes: 2))
                                      .toIso8601String(),
                            ),
                      ),
                    );
                  }
                  if (state is GoogleSignInSuccess) {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const UserInfoPage(),
                      ),
                    );
                  }
                  if (state is AuthError) {
                    AppSnackBar.showError(
                      context: context,
                      message: state.message,
                      duration: const Duration(seconds: 2),
                    );
                  }
                },
                builder: (context, state) {
                  if (state is AuthLoading) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  return Column(
                    children: [
                      SizedBox(
                        width: double.infinity,
                        height: 48,
                        child: Button(
                          color: AppColors.buttonPrimary,
                          text: "Get OTP",
                          onPressed: () {
                            context.read<AuthBloc>().add(
                              SendOTPEvent(
                                phoneNumber:
                                    "+${_selectedCountry.phoneCode}${phoneController.text}",
                              ),
                            );
                          },
                        ),
                      ),
                      SizedBox(height: height / 50),
                      Row(
                        children: [
                          Expanded(
                            child: Divider(
                              thickness: 1,
                              color: AppColors.greyBorder,
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(
                              horizontal: context.screenWidth / 15,
                            ),
                            child: const Text(
                              "Or continue with",
                              style: TextStyle(
                                fontWeight: FontWeight.normal,
                                fontSize: 17,
                              ),
                            ),
                          ),
                          Expanded(
                            child: Divider(
                              thickness: 1,
                              color: AppColors.greyBorder,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: height / 40),
                      SizedBox(
                        width: double.infinity,
                        height: 48,
                        child: OutlinedButton.icon(
                          icon: SvgPicture.asset(Assets.images.googleSvg.path),
                          label: Text(
                            "Login with google",
                            style: TextStyle(
                              color: AppColors.textPrimary,
                              fontWeight: FontWeight.bold,
                              fontSize: 17,
                            ),
                          ),
                          style: OutlinedButton.styleFrom(
                            side: BorderSide(color: AppColors.greyBorder),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(32),
                            ),
                          ),
                          onPressed: () {
                            context.read<AuthBloc>().add(
                              SignInWithGoogleEvent(),
                            );
                          },
                        ),
                      ),
                    ],
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _openCountryPicker(BuildContext context) {
    showDialog(
      context: context,
      builder:
          (context) => CustomCountryPicker(
            onCountrySelected: (Country country) {
              setState(() {
                _selectedCountry = country;
                countryController.text = country.name;
              });
            },
          ),
    );
  }
}
