import 'package:country_pickers/country.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:country_pickers/country_pickers.dart';
import 'package:lba/extension/screenSize.dart';
import 'package:lba/gen/assets.gen.dart';
import 'package:lba/screens/auth/cubit/auth_cubit.dart' as cubit;
import 'package:lba/screens/auth/otpVerifcation.dart';
import 'package:lba/widgets/button.dart';

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

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  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),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Color.fromARGB(255, 14, 63, 102),
                  ),),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Color.fromARGB(255, 14, 63, 102),
                      width: 2,
                    ),
                  ),
                ),
              ),

              const SizedBox(height: 16),

              TextField(
                controller: phoneController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: "Phone Number",
                  hintText: "_ _ _ _ _ _ _ _ _ _ _",
                  labelStyle: TextStyle(
                    color: Colors.black
                  ),
                  prefix: Text(
                    "+${_selectedCountry.phoneCode} ",
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Color.fromARGB(255, 14, 63, 102),
                      width: 2,
                    ),
                  ),
                ),
              ),

              const SizedBox(height: 16),
              InkWell(
                onTap: () {
                  setState(() {
                    keepSignedIn=!keepSignedIn;
                  });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Checkbox(
                      value: keepSignedIn,
                      activeColor: const Color.fromARGB(255, 14, 63, 102),
                      onChanged: (bool? value) {
                        setState(() {
                          keepSignedIn = value ?? false;
                        });
                      },
                    ),
                    const Text(
                      "Keep me signed in",
                      style: TextStyle(fontSize: 15),
                    ),
                  ],
                ),
              ),
              SizedBox(height: height / 50),
              BlocConsumer<cubit.AuthCubit, cubit.AuthState>(
                listener: (context, state) {
                  if (state is cubit.AuthSuccess) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) =>
                            OTPVerification(phoneNumber: phoneController.text),
                      ),
                    );
                  }
                  if (state is cubit.AuthError) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        duration: const Duration(seconds: 2),
                        backgroundColor: Colors.red,
                        content: Text(state.message),
                      ),
                    );
                  }
                },
                builder: (context, state) {
                  if (state is cubit.AuthLoading) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  return Column(
                    children: [
                      SizedBox(
                        width: double.infinity,
                        height: 48,
                        child: Button(
                          color: const Color.fromARGB(255, 30, 137, 221),
                          text: "Get OTP",
                          onPressed: () {
                            context.read<cubit.AuthCubit>().sendOTP(
                                  "+${_selectedCountry.phoneCode}${phoneController.text}",
                                );
                          },
                        ),
                      ),
                      SizedBox(height: height / 50),
                      Row(
                        children: [
                          const Expanded(
                            child: Divider(thickness: 1, color: Colors.grey),
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: context.screenWidth / 15),
                            child: const Text(
                              "Or continue with",
                              style: TextStyle(
                                  fontWeight: FontWeight.normal, fontSize: 17),
                            ),
                          ),
                          const Expanded(
                            child: Divider(thickness: 1, color: Colors.grey),
                          ),
                        ],
                      ),
                      SizedBox(height: height / 30),
                      SizedBox(
                        width: double.infinity,
                        height: 48,
                        child: OutlinedButton.icon(
                          icon: SvgPicture.asset(Assets.images.googleSvg.path),
                          label: const Text(
                            "Login with google",
                            style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                                fontSize: 17),
                          ),
                          style: OutlinedButton.styleFrom(
                            side: const BorderSide(color: Colors.grey),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(32),
                            ),
                          ),
                          onPressed: () {},
                        ),
                      ),
                    ],
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _openCountryPicker(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => Theme(
        data: Theme.of(context).copyWith(
          primaryColor: const Color.fromARGB(255, 14, 63, 102),
        ),
        child: CountryPickerDialog(
          title: const Text('Select Country'),
          searchCursorColor: const Color.fromARGB(255, 14, 63, 102),
          searchInputDecoration: const InputDecoration(
            hintText: 'Search...',
            prefixIcon: Icon(Icons.search),
          ),
          isSearchable: true,
          onValuePicked: (Country country) {
            setState(() {
              _selectedCountry = country;
              countryController.text = country.name;
            });
          },
          itemBuilder: _buildDialogItem,
        ),
      ),
    );
  }

  Widget _buildDialogItem(Country country) => Row(
    children: [
      CountryPickerUtils.getDefaultFlagImage(country),
      const SizedBox(width: 8),
      Text("+${country.phoneCode}"),
      const SizedBox(width: 8),
      Flexible(child: Text(country.name)),
    ],
  );
}