import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:lba/gen/assets.gen.dart';
import 'package:lba/screens/auth/cubit/auth_cubit.dart';
import 'package:lba/screens/auth/otpVerifcation.dart';
import 'package:lba/widgets/loginButton.dart';

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

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

class _LoginState extends State<Login> {
  final TextEditingController phoneController = TextEditingController();

  final List<Map<String, String>> flagList = [
    {"image": "assets/images/usa.png", "code": "+1"},
    {"image": "assets/images/usa.png", "code": "+98"},
    {"image": "assets/images/usa.png", "code": "+44"},
  ];

  int selectedIndex = 0;
  bool keepSignedIn = false;

  @override
  Widget build(BuildContext context) {
    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),
                ),
              ),
              const SizedBox(height: 24),
              const Text(
                "Login",
                style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              const Text("Please enter your phone number"),
              const SizedBox(height: 25),
              TextField(
                controller: phoneController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: "Phone Number",
                  labelStyle: const TextStyle(
                    color: Color.fromARGB(255, 61, 61, 61),
                  ),
                  hintText: "Phone Number",
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(
                      color: Color.fromARGB(255, 14, 63, 102),
                      width: 2,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(
                      color: Color.fromARGB(255, 14, 63, 102),
                    ),
                  ),
                  prefixIcon: Padding(
                    padding: const EdgeInsets.only(left: 10, right: 5),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton<int>(
                        value: selectedIndex,
                        items: List.generate(flagList.length, (index) {
                          return DropdownMenuItem<int>(
                            value: index,
                            child: Row(
                              children: [
                                Image.asset(
                                  flagList[index]["image"]!,
                                  width: 24,
                                  height: 24,
                                ),
                                const SizedBox(width: 6),
                                Text(
                                  flagList[index]["code"]!,
                                  style: const TextStyle(fontSize: 14),
                                ),
                              ],
                            ),
                          );
                        }),
                        onChanged: (value) {
                          setState(() {
                            selectedIndex = value!;
                          });
                        },
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              Row(
                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"),
                ],
              ),
              const SizedBox(height: 16),
              BlocConsumer<AuthCubit, AuthState>(
                listener: (context, state) {
                  if (state is AuthSuccess) {
                    Navigator.push(
                      context,  
                      MaterialPageRoute(
                        builder: (context) =>
                            OTPverifaction(phoneNumber: phoneController.text),
                      ),
                    );
                  } else if (state is AuthError) {   
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        duration: Duration(seconds: 2),
                        backgroundColor: Colors.red,
                        content: Text(state.message ?? "An error occurred"),
                      ),
                    );
                  }
                },
                builder: (context, state) {
                  if (state is AuthLoading) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  return Column(
                    children: [
                      SizedBox(
                        width: double.infinity,
                        height: 48,
                        child: LogInButton(
                          text: "Get OTP",
                          onPressed: () {
                            context.read<AuthCubit>().sendOTP(
                                  "${flagList[selectedIndex]["code"]}${phoneController.text}",
                                );
                          },
                        ),
                      ),
                      const SizedBox(height: 32),
                      Row(
                        children: [
                          const Expanded(
                            child: Divider(thickness: 1, color: Colors.grey),
                          ),
                          const Padding(
                            padding: EdgeInsets.symmetric(horizontal: 8.0),
                            child: Text(
                              "Or continue with",
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                          const Expanded(
                            child: Divider(thickness: 1, color: Colors.grey),
                          ),
                        ],
                      ),
                      const SizedBox(height: 32),
                      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),
                          ),
                          style: OutlinedButton.styleFrom(
                            side: const BorderSide(color: Colors.grey),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(32),
                            ),
                          ),
                          onPressed: () {},
                        ),
                      ),
                    ],
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}