import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_rentals/Screens/authScreen/OTP_Screen.dart';
import 'package:provider/provider.dart';
import '../../Notifier/RentalContactProvider .dart';
import '../../Utility/AdvancedSnackbar.dart';
import '../../Utility/CustomSnackbar.dart';
import '../../Utility/SharedpreferencesService.dart';

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

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

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _phoneController = TextEditingController();
  bool _isValid = false;
  bool _showError = false;
  bool _hasUserInteracted = false;

  final prefs = SharedPreferencesService.instance;

  void _validatePhone(String value) {
    setState(() {
      _isValid = RegExp(r'^[0-9]{10}$').hasMatch(value);

      // Reset error when user clears the field or starts typing
      if (value.isEmpty) {
        _showError = false;
      }
    });
  }

  void _checkValidation() {
    setState(() {
      _hasUserInteracted = true;
      // Only show error if field is not empty and invalid
      _showError = _phoneController.text.isNotEmpty && !_isValid;
    });
  }

  Future<void> _login(BuildContext context) async {
    // Check validation when button is pressed
    _checkValidation();

    // If invalid, don't proceed
    if (!_isValid) return;

    final rentalProvider = Provider.of<RentalProvider>(context, listen: false);
    final mob = _phoneController.text.trim();

    await rentalProvider.fetchRentalMobile(mob);

    //  Handle response - Check if error is "0" (string comparison)
    if (rentalProvider.response != null && rentalProvider.response!.error == "0") {
      AnimatedSnackBar.success(
        context: context,
        title: "OTP Sent",
        message: rentalProvider.response?.errorMsg ?? "OTP sent to your registered mobile number!",
      );

      // Navigate to OTP screen after a short delay
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => OtpScreen(mob: mob),
            ),
          );
        }
      });

    } else {
      CustomSnackBar.showWarning(
        context: context,
        title: "Login Failed",
        message: rentalProvider.response?.errorMsg.toString() ??
            "Mobile number not registered or invalid",
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final rentalProvider = Provider.of<RentalProvider>(context);

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          //  Fixed background image
          Positioned.fill(
            child: Image.asset(
              'assets/images/login_background.png',
              fit: BoxFit.cover,
            ),
          ),

          //  Dark overlay
          Positioned.fill(
            child: Container(color: Colors.black.withOpacity(0.4)),
          ),

          //  Foreground content with gradient
          Align(
            alignment: Alignment.bottomCenter,
            child: AnimatedPadding(
              duration: const Duration(milliseconds: 250),
              curve: Curves.easeOut,
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              child: Container(
                width: double.infinity,
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Colors.transparent,
                      Colors.black54,
                      Colors.black87,
                    ],
                  ),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const SizedBox(height: 60),
                    const Text(
                      "Rental Power,\nManaged in a Tap",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontFamily: "Poppins",
                        color: Colors.white,
                        fontSize: 35,
                        fontWeight: FontWeight.w400,
                        height: 1.3,
                      ),
                    ),
                    const SizedBox(height: 34),

                    // 🏷 Label above input
                    const Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: EdgeInsets.only(left: 12),
                        child: Text(
                          "Enter Registered Mobile No.",
                          style: TextStyle(
                            fontFamily: "Poppins",
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    // 📱 Mobile Input
                    TextField(
                      controller: _phoneController,
                      keyboardType: TextInputType.phone,
                      onChanged: _validatePhone,
                      maxLength: 10,
                      style: const TextStyle(color: Colors.black, fontFamily: "Poppins",fontSize: 14),
                      decoration: InputDecoration(
                        hintText: "Enter Mobile No.",
                        hintStyle: const TextStyle(color: Colors.grey,fontFamily: "Poppins", fontSize: 14),
                        filled: true,
                        fillColor: Colors.white,
                        counterText: "", // Remove character counter
                        contentPadding: const EdgeInsets.symmetric(
                            vertical: 16, horizontal: 20),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.5),
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                          borderSide: BorderSide(
                              color: _showError ? Colors.red : Colors.blue,
                              width: 2
                          ),
                        ),
                      ),
                    ),

                    // ⚠ Validation message - Only show after button press and if invalid
                    if (_showError)
                      const Padding(
                        padding: EdgeInsets.only(left: 12, top: 8),
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "*Invalid number. Enter your registered number.",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              color: Colors.redAccent,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ),

                    const SizedBox(height: 20),

                    // 🔘 Continue Button
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: (rentalProvider.isLoading)
                            ? null
                            : () => _login(context),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: _isValid
                              ? const Color(0xFF008CDE)
                              : const Color(0xFF266E99),
                          foregroundColor: Colors.white,
                          disabledBackgroundColor: const Color(0xFF266E99),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(30),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 16),
                        ),
                        child: rentalProvider.isLoading
                            ? const SizedBox(
                          height: 22,
                          width: 22,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation<Color>(
                                Colors.white),
                          ),
                        )
                            : Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 22),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "Continue",
                                style: TextStyle(
                                  fontFamily: "Poppins",
                                  color: _isValid
                                      ? const Color(0xFFFFFFFF)
                                      : const Color(0xFF03456C),
                                  fontSize: 16,
                                ),
                              ),
                              SvgPicture.asset(
                                "assets/svg/continue_ic.svg",
                                color: _isValid
                                    ? const Color(0xFFFFFFFF)
                                    : const Color(0xFF03456C),
                                height: 25,
                                width: 25,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 40),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _phoneController.dispose();
    super.dispose();
  }
}
