import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';

import '../../../constant/box_name.dart';
import '../../../controller/auth/captin/phone_helper_controller.dart';
import '../../../controller/local/phone_intel/intl_phone_field.dart';
import '../../../main.dart';
import '../../../print.dart';

class AuthScreen extends StatelessWidget {
  final String title;
  final String subtitle;
  final Widget form;
  // Using a more neutral, tech-themed animated logo
  final String logoUrl = 'assets/images/logo.gif';

  const AuthScreen({
    super.key,
    required this.title,
    required this.subtitle,
    required this.form,
  });

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(LoginDriverController());
    return Scaffold(
      body: Container(
        // UPDATED: Changed gradient colors to a green theme
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.teal.shade700, Colors.green.shade600],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        child: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(logoUrl, height: 120),
                const SizedBox(height: 20),
                Text(
                  title,
                  style: const TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
                const SizedBox(height: 10),
                Text(
                  subtitle,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 16, color: Colors.white.withOpacity(0.8)),
                ),
                const SizedBox(height: 30),
                GetBuilder<LoginDriverController>(builder: (context) {
                  return box.read(BoxName.isTest).toString() == '0'
                      ? Container(
                          margin: const EdgeInsets.all(16),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 24, vertical: 32),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(20),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black12,
                                blurRadius: 12,
                                offset: const Offset(0, 6),
                              ),
                            ],
                          ),
                          child: Form(
                            key: controller.formKey,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: [
                                // Title

                                Text(
                                  'Please login to continue',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.grey[600],
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                                const SizedBox(height: 32),

                                // Email Field
                                TextFormField(
                                  keyboardType: TextInputType.emailAddress,
                                  controller: controller.emailController,
                                  decoration: InputDecoration(
                                    labelText: 'Email'.tr,
                                    hintText: 'Enter your email address'.tr,
                                    prefixIcon:
                                        const Icon(Icons.email_outlined),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                  ),
                                  validator: (value) => value == null ||
                                          value.isEmpty ||
                                          !value.contains('@') ||
                                          !value.contains('.')
                                      ? 'Enter a valid email'.tr
                                      : null,
                                ),
                                const SizedBox(height: 20),

                                // Password Field
                                TextFormField(
                                  obscureText: true,
                                  controller: controller.passwordController,
                                  decoration: InputDecoration(
                                    labelText: 'Password'.tr,
                                    hintText: 'Enter your password'.tr,
                                    prefixIcon: const Icon(Icons.lock_outline),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                  ),
                                  validator: (value) =>
                                      value == null || value.isEmpty
                                          ? 'Enter your password'.tr
                                          : null,
                                ),
                                const SizedBox(height: 24),

                                // Submit Button
                                GetBuilder<LoginDriverController>(
                                  builder: (controller) => controller.isloading
                                      ? const Center(
                                          child: CircularProgressIndicator())
                                      : SizedBox(
                                          height: 50,
                                          child: ElevatedButton(
                                            style: ElevatedButton.styleFrom(
                                              backgroundColor:
                                                  Colors.blueAccent,
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(12),
                                              ),
                                            ),
                                            onPressed: () {
                                              if (controller
                                                  .formKey.currentState!
                                                  .validate()) {
                                                controller.logintest(
                                                  controller
                                                      .passwordController.text
                                                      .trim(),
                                                  controller
                                                      .emailController.text
                                                      .trim(),
                                                );
                                              }
                                            },
                                            child: Text(
                                              'Login'.tr,
                                              style:
                                                  const TextStyle(fontSize: 16),
                                            ),
                                          ),
                                        ),
                                ),

                                const SizedBox(height: 16),

                                // Optional: Forgot Password / Create Account
                              ],
                            ),
                          ),
                        )
                      : Card(
                          elevation: 8,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16)),
                          child: Padding(
                            padding: const EdgeInsets.all(24.0),
                            child: form,
                          ),
                        );
                })
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// --- UI Screens ---

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

class _PhoneNumberScreenState extends State<PhoneNumberScreen> {
  final _phoneController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;

  void _submit() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isLoading = true);
      final rawPhone = _phoneController.text.trim().replaceFirst('+', '');
      final success = await PhoneAuthHelper.sendOtp(rawPhone);
      if (success && mounted) {
        Get.to(() => OtpVerificationScreen(phoneNumber: rawPhone));
      }
      if (mounted) setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AuthScreen(
      title: 'welcome to intaleq'.tr,
      subtitle: 'login or register subtitle'.tr,
      form: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // TextFormField(
            //   controller: _phoneController,
            //   decoration: InputDecoration(
            //     labelText: 'phone number label'.tr,
            //     prefixIcon:
            //         Icon(Icons.phone_android, color: Colors.teal.shade400),
            //     border:
            //         OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
            //   ),
            //   keyboardType: TextInputType.phone,
            //   validator: (v) => v!.isEmpty ? 'phone number required'.tr : null,
            // ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: IntlPhoneField(
                // languageCode: 'ar',
                showCountryFlag: false,
                flagsButtonMargin: EdgeInsets.only(right: 8),
                flagsButtonPadding: EdgeInsets.all(4),
                dropdownDecoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(8)),
                // controller: _phoneController,
                decoration: InputDecoration(
                  labelText: 'Phone Number'.tr,
                  border: const OutlineInputBorder(
                    borderSide: BorderSide(),
                  ),
                ),
                initialCountryCode: 'SY',
                onChanged: (phone) {
                  // Properly concatenate country code and number
                  _phoneController.text = phone.completeNumber.toString();
                  Log.print(' phone.number: ${phone.number}');
                  print("Formatted phone number: ${_phoneController.text}");
                },
                validator: (phone) {
                  // Check if the phone number is not null and is valid
                  if (phone == null || phone.completeNumber.isEmpty) {
                    return 'Please enter your phone number';
                  }

                  // Extract the phone number (excluding the country code)
                  final number = phone.completeNumber.toString();

                  // Check if the number length is exactly 11 digits
                  if (number.length != 13) {
                    return 'Phone number must be exactly 11 digits long';
                  }

                  // If all validations pass, return null
                  return null;
                },
              ),
            ),

            const SizedBox(height: 24),
            _isLoading
                ? const CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: _submit,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.teal,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                      minimumSize: const Size(double.infinity, 50),
                    ),
                    child: Text('send otp button'.tr),
                  ),
          ],
        ),
      ),
    );
  }
}

class OtpVerificationScreen extends StatefulWidget {
  final String phoneNumber;
  const OtpVerificationScreen({super.key, required this.phoneNumber});
  @override
  State<OtpVerificationScreen> createState() => _OtpVerificationScreenState();
}

class _OtpVerificationScreenState extends State<OtpVerificationScreen> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _otpControllers = TextEditingController();
  // final List<FocusNode> _focusNodes = List.generate(5, (_) => FocusNode());
  bool _isLoading = false;

  @override
  void dispose() {
    // for (var controller in _otpControllers) {
    //   controller.dispose();
    // }
    // for (var node in _focusNodes) {
    //   node.dispose();
    // }
    super.dispose();
  }

  void _submit() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isLoading = true);
      final otp = _otpControllers.text;
      await PhoneAuthHelper.verifyOtp(widget.phoneNumber, otp);
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Widget _buildOtpInput() {
    return Form(
      key: _formKey,
      child: Container(
        width: 200,
        height: 50,
        decoration: BoxDecoration(
          color: Colors.grey.shade200,
          shape: BoxShape.circle,
        ),
        child: Center(
          child: TextFormField(
            controller: _otpControllers,
            // focusNode: _focusNodes[index],
            textAlign: TextAlign.center,
            keyboardType: TextInputType.number,
            maxLength: 5,
            style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            decoration: const InputDecoration(
              counterText: "",
              border: InputBorder.none,
              contentPadding: EdgeInsets.zero,
            ),
            onChanged: (value) {},
            validator: (v) => v!.isEmpty ? '' : null,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AuthScreen(
      title: 'verify your number title'.tr,
      subtitle:
          'otp sent subtitle'.trParams({'phoneNumber': widget.phoneNumber}),
      form: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildOtpInput(),
          const SizedBox(height: 30),
          _isLoading
              ? const CircularProgressIndicator()
              : ElevatedButton(
                  onPressed: _submit,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.teal,
                    foregroundColor: Colors.white,
                    minimumSize: const Size(double.infinity, 50),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                  ),
                  child: Text('verify and continue button'.tr),
                ),
        ],
      ),
    );
  }
}

class RegistrationScreen extends StatefulWidget {
  final String phoneNumber;
  const RegistrationScreen({super.key, required this.phoneNumber});
  @override
  State<RegistrationScreen> createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends State<RegistrationScreen> {
  final _formKey = GlobalKey<FormState>();
  final _firstNameController = TextEditingController();
  final _lastNameController = TextEditingController();
  final _emailController = TextEditingController();
  bool _isLoading = false;

  void _submit() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isLoading = true);
      await PhoneAuthHelper.registerUser(
        phoneNumber: widget.phoneNumber,
        firstName: _firstNameController.text.trim(),
        lastName: _lastNameController.text.trim(),
        email: _emailController.text.trim(),
      );
      if (mounted) setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AuthScreen(
      title: 'one last step title'.tr,
      subtitle: 'complete profile subtitle'.tr,
      form: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              controller: _firstNameController,
              decoration: InputDecoration(
                  labelText: 'first name label'.tr,
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(12)))),
              validator: (v) => v!.isEmpty ? 'first name required'.tr : null,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _lastNameController,
              decoration: InputDecoration(
                  labelText: 'last name label'.tr,
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(12)))),
              validator: (v) => v!.isEmpty ? 'last name required'.tr : null,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _emailController,
              decoration: InputDecoration(
                  labelText: 'email optional label'.tr,
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(12)))),
              keyboardType: TextInputType.emailAddress,
            ),
            const SizedBox(height: 24),
            _isLoading
                ? const CircularProgressIndicator()
                : ElevatedButton(
                    onPressed: _submit,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.teal,
                      foregroundColor: Colors.white,
                      minimumSize: const Size(double.infinity, 50),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12)),
                    ),
                    child: Text('complete registration button'.tr),
                  ),
          ],
        ),
      ),
    );
  }
}
