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';

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 _isDirty = false;

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

  Future<void> _login(BuildContext context) async {
    final rentalProvider =
    Provider.of<RentalContactProvider>(context, listen: false);
    final mob = _phoneController.text.trim();

    await rentalProvider.fetchRentalContactData(
      context,
      "4d21382d9e1c4d6e0b7c426d53d89b6b7d48078877f185289092e6fa13bac4b11d417d37738b20b34151b8e638625b3ec013",
      "5",
      mob,
    );

    // ✅ Handle response
    if (rentalProvider.rentalContact != null &&
        rentalProvider.rentalContact!.error == 0) {
      AnimatedSnackBar.success(
        context: context,
        title: "Login Success",
        message: "${rentalProvider.rentalContact?.message} OTP: ${rentalProvider.rentalContact?.otp}" ?? "Login Success",
      );

      // Navigate to OTP screen
      Navigator.pushReplacement(
        context,
        PageRouteBuilder(
          pageBuilder: (_, __, ___) => OtpScreen(
            mob: mob,
            otp: rentalProvider.rentalContact!.otp ?? 0,
          ),
          transitionsBuilder: (_, animation, __, child) {
            return FadeTransition(opacity: animation, child: child);
          },
          transitionDuration: const Duration(milliseconds: 600),
        ),
      );

    } else {
      CustomSnackBar.showWarning(
        context: context,
        message: rentalProvider.rentalContact?.message ??
            rentalProvider.errorMessage ??
            "Login failed",
        title: "Login Status",
      );
    }
  }

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

    return Scaffold(
      resizeToAvoidBottomInset: false, // prevents background image resize
      body: Stack(
        children: [
          // 🏙️ Fixed background image
          Positioned.fill(
            child: Image.asset(
              'assets/images/background.jpg',
              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(
                        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(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    // 📱 Mobile Input
                    TextField(
                      controller: _phoneController,
                      keyboardType: TextInputType.phone,
                      onChanged: _validatePhone,
                      style: const TextStyle(color: Colors.black),
                      decoration: InputDecoration(
                        hintText: "Enter Mobile No.",
                        hintStyle: const TextStyle(color: Colors.grey),
                        filled: true,
                        fillColor: Colors.white,
                        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:
                          const BorderSide(color: Colors.blue, width: 2),
                        ),
                      ),
                    ),

                    // ⚠️ Validation message
                    if (_isDirty && !_isValid)
                      const Padding(
                        padding: EdgeInsets.only(left: 12, top: 8),
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "*Invalid number. Enter your registered number.",
                            style: TextStyle(
                              color: Colors.redAccent,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ),

                    const SizedBox(height: 20),

                    // 🔘 Continue Button
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: (!_isValid || 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(
                                  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),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
