// lib/screens/auth/login.dart
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:intl_phone_field/intl_phone_field.dart';
import 'package:shared_preferences/shared_preferences.dart';

// --- localization helper used in your project
import 'package:fl_ks_smart_society_user/localization/localization_const.dart';

import '../../theme/theme.dart'; // keep your theme import (colors, text styles, paddings)

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

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

class _LoginScreenState extends State<LoginScreen> {
  // controllers
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _forgotPhoneController = TextEditingController();

  // state
  String phoneNumber = "";
  bool isLoading = false;
  DateTime? backPressTime;
  bool _isOtpLogin = false; // 🔁 toggle between password and OTP login
  bool _isTermsAccepted = false; // ✅ must be checked before login

  // backend endpoints - adjust if needed
  final String backendLoginUrl = "https://gelite.asia/api/login.php";
  final String backendForgotUrl = "https://gelite.asia/api/forgot_password.php";

  // ---------------- SharedPreferences save ----------------
  Future<void> _saveUserToPrefs(Map<String, dynamic> user) async {
    print("💾 Saving user to SharedPreferences: $user");
    final prefs = await SharedPreferences.getInstance();
    if (user['phone_no'] != null) {
      await prefs.setString('phone_no', user['phone_no'].toString());
      print("✅ Saved phone_no: ${user['phone_no']}");
    }
    if (user['id'] != null) {
      final id = int.tryParse(user['id'].toString()) ?? 0;
      await prefs.setInt('id', id);
      print("✅ Saved id: $id");
    }
    if (user['name'] != null) {
      await prefs.setString('name', user['name'].toString());
      print("✅ Saved name: ${user['name']}");
    }
    if (user['role'] != null) {
      await prefs.setString('role', user['role'].toString());
      print("✅ Saved role: ${user['role']}");
    }
    if (user['profile_photo'] != null) {
      await prefs.setString('profile_photo', user['profile_photo'].toString());
      print("✅ Saved profile_photo");
    }
    if (user['vertical'] != null) {
      await prefs.setString('vertical', user['vertical'].toString());
      print("✅ Saved vertical: ${user['vertical']}");
    }
    if (user['fcm_token'] != null) {
      await prefs.setString('fcm_token', user['fcm_token'].toString());
      print("✅ Saved fcm_token");
    }
    if (user['created_at'] != null) {
      await prefs.setString('created_at', user['created_at'].toString());
      print("✅ Saved created_at: ${user['created_at']}");
    }
    if (user['token'] != null) {
      await prefs.setString('token', user['token'].toString());
      print("✅ Saved token");
    }
    print("💾 User saved to SharedPreferences (complete)");
  }

  Map<String, dynamic> _extractUserFromResponse(Map<String, dynamic> respJson) {
    print("🔍 Extracting user from response JSON: $respJson");
    Map<String, dynamic> user = {};
    if (respJson['data'] != null) {
      if (respJson['data'] is Map && respJson['data']['user'] != null) {
        user = Map<String, dynamic>.from(respJson['data']['user']);
        print("✅ Extracted user from data.user");
      } else if (respJson['data'] is Map) {
        user = Map<String, dynamic>.from(respJson['data']);
        print("✅ Extracted user from data");
      }
    }
    print("👤 Final extracted user map: $user");
    return user;
  }

  // ---------------- Password login ----------------
  Future<void> loginWithPassword() async {
    if (phoneNumber.isEmpty || _passwordController.text.isEmpty) {
      _showSnack("phone_no and password are required", isError: true);
      print("❌ [Password Login] validation failed: phoneNumber or password empty");
      return;
    }

    setState(() => isLoading = true);

    final body = {
      "phone_no": phoneNumber,
      "password": _passwordController.text,
    };
    print("📤 [Password Login] Request body => ${jsonEncode(body)}");

    try {
      final resp = await http.post(
        Uri.parse(backendLoginUrl),
        headers: {"Content-Type": "application/json"},
        body: jsonEncode(body),
      );

      print(
        "📥 [Password Login] Response => statusCode: ${resp.statusCode}, body: ${resp.body}",
      );

      if (resp.statusCode == 200) {
        final jsonResp = jsonDecode(resp.body);
        print("🔎 [Password Login] Decoded JSON => $jsonResp");

        if (jsonResp['status'] == 'success') {
          final user = _extractUserFromResponse(jsonResp);
          await _saveUserToPrefs(user);
          _showSnack("Login successful");
          print("✅ [Password Login] Success - navigating to /bottombar");
          if (!mounted) return;
          Navigator.pushReplacementNamed(context, '/bottombar');
        } else {
          final msg = jsonResp['message']?.toString() ?? "Invalid credentials";
          _showSnack(msg, isError: true);
          print("⚠️ [Password Login] Failure => $msg");
        }
      } else {
        _showSnack("Server error: ${resp.statusCode}", isError: true);
        print("❌ [Password Login] Server error: ${resp.statusCode}");
      }
    } catch (e) {
      print("❌ [Password Login] Exception => $e");
      _showSnack("Network error", isError: true);
    } finally {
      if (mounted) setState(() => isLoading = false);
      print("ℹ️ [Password Login] isLoading set to false");
    }
  }

  // ---------------- Go to OTP Screen ----------------
  void _goToOtpScreen() {
    print("👉 [UI] Login with OTP tapped (via button)");

    if (phoneNumber.isEmpty) {
      _showSnack("Enter mobile number", isError: true);
      print("❌ [OTP Navigate] Phone number empty");
      return;
    }

    print("➡️ [OTP Navigate] Navigating to /otp with phoneNumber: $phoneNumber");
    Navigator.pushNamed(
      context,
      '/otp',
      arguments: {
        "phone_no": phoneNumber, // 👈 consistent key used for OTP screen
      },
    );
  }

  // ---------------- Forgot password (logic only, no UI) ----------------
  Future<void> forgotPassword() async {
    final phone = _forgotPhoneController.text.trim();
    if (phone.isEmpty) {
      _showSnack("Enter phone number", isError: true);
      print("❌ [Forgot Password] Phone number empty");
      return;
    }

    setState(() => isLoading = true);

    final body = {"phone_no": phone};
    print("📤 [Forgot Password] Request body => ${jsonEncode(body)}");

    try {
      final resp = await http.post(
        Uri.parse(backendForgotUrl),
        headers: {"Content-Type": "application/json"},
        body: jsonEncode(body),
      );

      print(
        "📥 [Forgot Password] Response => statusCode: ${resp.statusCode}, body: ${resp.body}",
      );

      if (resp.statusCode == 200) {
        final jsonResp = jsonDecode(resp.body);
        print("🔎 [Forgot Password] Decoded JSON => $jsonResp");

        final msg = jsonResp['message']?.toString() ?? "Check your phone";
        _showSnack(msg);
        print("✅ [Forgot Password] Message => $msg");
      } else {
        _showSnack("Server error: ${resp.statusCode}", isError: true);
        print("❌ [Forgot Password] Server error: ${resp.statusCode}");
      }
    } catch (e) {
      print("❌ [Forgot Password] Exception => $e");
      _showSnack("Network error", isError: true);
    } finally {
      if (mounted) setState(() => isLoading = false);
      print("ℹ️ [Forgot Password] isLoading set to false");
    }
  }

  // ---------------- UI ----------------
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);

    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) {
        bool backStatus = onWillPop();
        if (backStatus) {
          print("🚪 Exiting app from LoginScreen back press");
          exit(0);
        }
      },
      child: AnnotatedRegion(
        value: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
        ),
        child: Scaffold(
          body: Stack(
            children: [
              Container(
                height: size.height,
                width: size.width,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("assets/auth/bg-image.png"),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      stops: const [0.37, 1.0],
                      colors: [
                        whiteColor,
                        primaryColor.withOpacity(0.5),
                      ],
                    ),
                  ),
                  child: ListView(
                    physics: const BouncingScrollPhysics(),
                    padding: const EdgeInsets.all(fixPadding * 2.0),
                    children: [
                      heightBox(kToolbarHeight),
                      loginContent(),
                      heightSpace,
                      heightSpace,
                      heightSpace,

                      // Top-right toggle: Login with OTP / Login with Password
                      Padding(
                        padding: const EdgeInsets.only(right: 4.0, bottom: 8.0),
                        child: Row(
                          children: [
                            const Spacer(),
                            InkWell(
                              onTap: () {
                                setState(() {
                                  _isOtpLogin = !_isOtpLogin;
                                });
                                print(
                                  "👉 [UI] Toggled login mode to: ${_isOtpLogin ? 'OTP' : 'Password'}",
                                );
                              },
                              child: Text(
                                _isOtpLogin
                                    ? "Login with Password"
                                    : "Login with OTP",
                                style: regular16Black.copyWith(
                                  decoration: TextDecoration.underline,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      mobileNumberField(),
                      heightSpace,

                      if (_isOtpLogin)
                        const Padding(
                          padding: EdgeInsets.symmetric(vertical: 6.0),
                          child: Text(
                            "*we will send OTP for verification",
                            style: TextStyle(fontSize: 13),
                          ),
                        ),

                      if (!_isOtpLogin) ...[
                        // Password field (hidden in OTP mode)
                        passwordField(),

                        // (Forgot Password UI removed)

                        heightSpace,
                        heightSpace,
                      ] else
                        heightSpace,

                      // Terms checkbox (compulsory)
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Checkbox(
                            value: _isTermsAccepted,
                            onChanged: (value) {
                              setState(() {
                                _isTermsAccepted = value ?? false;
                              });
                              print(
                                "📝 [UI] Terms checkbox tapped => $_isTermsAccepted",
                              );
                            },
                          ),
                          Expanded(
                            child: Wrap(
                              children: [
                                const Text("I agree "),
                                GestureDetector(
                                  onTap: () {
                                    print(
                                      "👉 [UI] Terms & Conditions tapped - navigating to /termsAndCondition",
                                    );
                                    Navigator.pushNamed(
                                      context,
                                      '/termsAndCondition',
                                    );
                                  },
                                  child: const Text(
                                    "Terms & Conditions",
                                    style: TextStyle(
                                      decoration: TextDecoration.underline,
                                    ),
                                  ),
                                ),
                                const Text(" & "),
                                GestureDetector(
                                  onTap: () {
                                    print(
                                      "👉 [UI] Privacy Policy tapped - navigating to /privacyPolicy",
                                    );
                                    Navigator.pushNamed(
                                      context,
                                      '/privacyPolicy',
                                    );
                                  },
                                  child: const Text(
                                    "Privacy Policy",
                                    style: TextStyle(
                                      decoration: TextDecoration.underline,
                                    ),
                                  ),
                                ),
                                const Text("."),
                              ],
                            ),
                          ),
                        ],
                      ),

                      heightSpace,
                      heightSpace,

                      // Login button (mode-dependent)
                      GestureDetector(
                        onTap: () {
                          print(
                            "👉 [UI] Login button tapped - mode: ${_isOtpLogin ? 'OTP' : 'Password'}",
                          );

                          // ✅ Check terms acceptance first
                          if (!_isTermsAccepted) {
                            _showSnack(
                              "Please agree to Terms & Conditions & Privacy Policy",
                              isError: true,
                            );
                            print(
                              "❌ [Login] Blocked - terms not accepted",
                            );
                            return;
                          }

                          if (_isOtpLogin) {
                            // OTP mode → go to OTP screen
                            _goToOtpScreen();
                          } else {
                            // Password mode → password login
                            loginWithPassword();
                          }
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: fixPadding * 2.0,
                            vertical: fixPadding * 1.1,
                          ),
                          decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(10.0),
                            boxShadow: buttonShadow,
                          ),
                          child: Text(
                            tr(context, 'login.login'),
                            style: medium20White,
                            overflow: TextOverflow.ellipsis,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),

                      heightSpace,
                      heightSpace,

                      // Become Member (outline style)
                      GestureDetector(
                        onTap: () {
                          print(
                            "👉 [UI] Become Member tapped, navigating to /register",
                          );
                          Navigator.pushNamed(context, '/register');
                        },
                        child: Container(
                          margin: const EdgeInsets.only(top: 12.0),
                          padding: const EdgeInsets.symmetric(
                            horizontal: fixPadding * 2.0,
                            vertical: fixPadding * 1.0,
                          ),
                          decoration: BoxDecoration(
                            color: whiteColor,
                            borderRadius: BorderRadius.circular(10.0),
                            border: Border.all(color: primaryColor),
                            boxShadow: boxShadow,
                          ),
                          child: Text(
                            "Become Member",
                            style: medium16Black,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),

                      heightSpace,
                      heightSpace,

                      // Continue as Guest centered (bolder red)
                      Center(
                        child: TextButton(
                          style: TextButton.styleFrom(
                            foregroundColor: Colors.red.shade800,
                          ),
                          onPressed: () {
                            print(
                              "👉 [UI] Continue as Guest tapped, navigating to /bottombar",
                            );
                            Navigator.pushReplacementNamed(
                              context,
                              '/bottombar',
                            );
                          },
                          child: const Text(
                            "Continue as Guest",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 20,
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(height: 30),
                    ],
                  ),
                ),
              ),

              // Simple loader
              if (isLoading)
                Container(
                  color: Colors.black.withOpacity(0.2),
                  child: const Center(
                    child: CircularProgressIndicator(),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget loginContent() {
    return Column(
      children: [
        Text(
          tr(context, 'login.login'),
          style: medium20Primary,
          textAlign: TextAlign.center,
        ),
        height5Space,
        Text(
          tr(context, 'login.welcome_text'),
          style: regular16Grey,
          textAlign: TextAlign.center,
        )
      ],
    );
  }

  Widget mobileNumberField() {
    return Container(
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: boxShadow,
      ),
      padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      child: IntlPhoneField(
        cursorColor: primaryColor,
        initialCountryCode: "IN",
        disableLengthCheck: true,
        dropdownIcon: const Icon(
          Icons.arrow_drop_down,
          size: 0,
          color: Colors.transparent,
        ),
        dropdownTextStyle:
        const TextStyle(fontSize: 1, color: Colors.transparent),
        style: regular16Black,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          border: InputBorder.none,
          focusedBorder: focusedBorder,
          isDense: true,
          hintText: tr(context, 'login.enter_mobile_number'),
          hintStyle: regular16Grey,
          contentPadding:
          const EdgeInsets.symmetric(vertical: fixPadding * 1.35),
          counterText: "",
        ),
        onChanged: (value) {
          phoneNumber = value.completeNumber;
          print("📱 [UI] Phone entered → $phoneNumber");
        },
      ),
    );
  }

  Widget passwordField() {
    return Container(
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: boxShadow,
      ),
      child: TextField(
        controller: _passwordController,
        obscureText: true,
        style: regular16Black,
        decoration: InputDecoration(
          border: InputBorder.none,
          focusedBorder: focusedBorder,
          isDense: true,
          hintText: tr(context, 'login.enter_password'),
          hintStyle: regular16Grey,
          contentPadding: const EdgeInsets.symmetric(
            vertical: fixPadding * 1.35,
            horizontal: fixPadding,
          ),
          counterText: "",
        ),
        onChanged: (val) {
          print("🔐 [UI] Password changed (length: ${val.length})");
        },
      ),
    );
  }

  void _openForgotDialog() {
    showDialog(
      context: context,
      builder: (c) {
        return AlertDialog(
          title: const Text("Forgot Password"),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text("Enter your registered phone number"),
              TextField(
                controller: _forgotPhoneController,
                keyboardType: TextInputType.phone,
                decoration: const InputDecoration(
                  hintText: "Phone number with country code",
                ),
                onChanged: (val) {
                  print(
                    "📱 [Forgot Password Dialog] Phone input changed => $val",
                  );
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                print("❌ [Forgot Password Dialog] Cancel tapped");
                Navigator.pop(c);
              },
              child: const Text("Cancel"),
            ),
            ElevatedButton(
              onPressed: () {
                print("✅ [Forgot Password Dialog] Send tapped");
                Navigator.pop(c);
                forgotPassword();
              },
              child: const Text("Send"),
            ),
          ],
        );
      },
    );
  }

  void _showSnack(String message, {bool isError = false}) {
    if (!mounted) return;
    print("🔔 [SnackBar] ${isError ? 'ERROR' : 'INFO'} => $message");
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  bool onWillPop() {
    DateTime now = DateTime.now();
    if (backPressTime == null ||
        now.difference(backPressTime!) >= const Duration(seconds: 2)) {
      backPressTime = now;
      print("🔙 [Back Press] First back press - show exit message");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: originalBlackColor,
          content: Text(
            tr(context, 'exit_app.exit_text'),
            style: medium15White,
          ),
          behavior: SnackBarBehavior.floating,
          duration: const Duration(milliseconds: 1500),
        ),
      );
      return false;
    } else {
      print("🔙 [Back Press] Second back press within 2s - exit allowed");
      return true;
    }
  }

  @override
  void dispose() {
    print("🧹 Disposing LoginScreen controllers");
    _passwordController.dispose();
    _forgotPhoneController.dispose();
    super.dispose();
  }
}
