// lib/screens/auth/login.dart
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:intl_phone_field/intl_phone_field.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:page_transition/page_transition.dart';

// your app-specific imports (localization/theme & bottom bar)
import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';
import 'package:fl_sevengen_society_user_app/screens/auth/otp.dart';
import 'package:fl_sevengen_society_user_app/screens/bottom_bar.dart';

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

enum LoginMode { password, otp }

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _phoneController =
  TextEditingController(); // holds the national number (usually)
  final TextEditingController _passwordController = TextEditingController();

  String _countryDialCode = '91'; // store without plus
  bool _loading = false;
  DateTime? backPressTime;
  LoginMode _mode = LoginMode.password;

  // guard so OTP success is only handled once
  bool _otpHandled = false;

  // T&C + Privacy checkbox
  bool _agreedToTerms = false;

  final FirebaseAuth _auth = FirebaseAuth.instance;

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

  // --------------------------
  // Phone helpers
  // --------------------------
  String _rawDigits(String input) => input.replaceAll(RegExp(r'[^0-9]'), '');

  String? _local10(String input) {
    final d = _rawDigits(input);
    if (d.length >= 10) return d.substring(d.length - 10);
    return null;
  }

  String _e164FromLocal(String local10) {
    final code =
    _countryDialCode.replaceAll('+', '').replaceAll(RegExp(r'[^0-9]'), '');
    return '+$code$local10';
  }

  String? _validateAndGetLocal() {
    final raw = _phoneController.text.trim();
    return _local10(raw);
  }

  // --------------------------
  // Success detection helper
  // --------------------------
  bool _isSuccessResponse(Map<String, dynamic> jsonResp) {
    if (jsonResp.containsKey('success')) {
      final s = jsonResp['success'];
      if (s == true || s == 1 || s == '1') return true;
    }
    if (jsonResp.containsKey('status')) {
      final st = jsonResp['status']?.toString().toLowerCase();
      if (st == 'success' || st == '1') return true;
    }
    return false;
  }

  // --------------------------
  // Robust navigation helper
  // --------------------------
  void _goToBottomBar() {
    print('DEBUG: _goToBottomBar called');
    try {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        try {
          print(
              'DEBUG: trying PageTransition to BottomBar using rootNavigator');
          Navigator.of(context, rootNavigator: true).pushAndRemoveUntil(
            PageTransition(
              type: PageTransitionType.rightToLeft,
              child: BottomBar(),
            ),
                (route) => false,
          );
        } catch (e) {
          print(
              'DEBUG: PageTransition failed -> $e. Falling back to MaterialPageRoute');
          try {
            Navigator.of(context, rootNavigator: true).pushAndRemoveUntil(
              MaterialPageRoute(builder: (_) => BottomBar()),
                  (route) => false,
            );
          } catch (e2, st2) {
            print('DEBUG: MaterialPageRoute navigation failed -> $e2');
            print(st2);
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Navigation error: $e2')),
            );
          }
        }
      });
    } catch (e, st) {
      print('DEBUG: _goToBottomBar outer error -> $e');
      print(st);
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Navigation error: $e')));
    }
  }

  // --------------------------
  // Login flows
  // --------------------------
  Future<void> _loginWithPassword() async {
    final local = _validateAndGetLocal();
    final password = _passwordController.text.trim();

    if (local == null || password.isEmpty) {
      _showSnack(getTranslate(context, 'login.enter_mobile_number'));
      return;
    }

    // Block if T&C not accepted
    if (!_agreedToTerms) {
      _showSnack('Please agree to Terms & Conditions and Privacy Policy.');
      return;
    }

    setState(() => _loading = true);
    try {
      final resp = await http.post(
        Uri.parse('https://rmbferodeunited.in/api/login.php'),
        body: {
          'phone': local, // only 10 digits
          'password': password,
        },
      );
      final Map<String, dynamic> jsonResp = json.decode(resp.body);

      if (_isSuccessResponse(jsonResp)) {
        final user = jsonResp['user'] ?? jsonResp;
        print('DEBUG: loginWithPassword success -> user: $user');
        await _saveUserToPrefs(user);
        await _sendFirebaseTokenToServer(local);
        _goToBottomBar();
      } else {
        final msg = jsonResp['message']?.toString() ?? 'Login failed';
        print(
          'DEBUG: loginWithPassword backend failure -> $msg | full response: ${resp.body}',
        );
        _showSnack(msg);
      }
    } catch (e, st) {
      print('DEBUG: loginWithPassword exception -> $e');
      print(st);
      _showSnack('Network error: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  Future<void> _startPhoneAuth() async {
    final local = _validateAndGetLocal();
    if (local == null) {
      _showSnack(getTranslate(context, 'login.enter_mobile_number'));
      return;
    }

    // Block if T&C not accepted
    if (!_agreedToTerms) {
      _showSnack('Please agree to Terms & Conditions and Privacy Policy.');
      return;
    }

    final e164 = _e164FromLocal(local);

    setState(() => _loading = true);
    await _auth.verifyPhoneNumber(
      phoneNumber: e164,
      timeout: const Duration(seconds: 60),
      verificationCompleted: (PhoneAuthCredential credential) async {
        try {
          final userCred = await _auth.signInWithCredential(credential);
          if (userCred.user != null) {
            print('DEBUG: Firebase auto verification succeeded for $e164');
            if (!_otpHandled) {
              _otpHandled = true;
              print('DEBUG: auto verification handling for local: $local');
              await _promptForPasswordAndLogin(local);
            } else {
              print(
                'DEBUG: auto verification received but _otpHandled==true; ignoring.',
              );
            }
          }
        } catch (e, st) {
          print('DEBUG: verificationCompleted exception -> $e');
          print(st);
          _showSnack('Auto verification failed: $e');
        } finally {
          setState(() => _loading = false);
        }
      },
      verificationFailed: (FirebaseException e) {
        print('DEBUG: verifyPhoneNumber failed -> ${e.message}');
        _showSnack('Verification failed: ${e.message}');
        setState(() => _loading = false);
      },
      codeSent: (String verificationId, int? resendToken) {
        print('DEBUG: codeSent; verificationId: $verificationId for $e164');
        setState(() => _loading = false);

        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => OTPScreen(
              verificationId: verificationId,
              phoneNumber: e164,
              onVerified: () async {
                if (_otpHandled) {
                  print(
                      'DEBUG: onVerified called but _otpHandled==true, ignoring.');
                  return;
                }
                _otpHandled = true;

                print(
                  'DEBUG: onVerified first-time handling for local phone: $local',
                );
                print(
                  'DEBUG: entering _promptForPasswordAndLogin for $local',
                );

                await _promptForPasswordAndLogin(local);

                print(
                  'DEBUG: leaving _promptForPasswordAndLogin for $local',
                );
              },
            ),
          ),
        );
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        print('DEBUG: codeAutoRetrievalTimeout: $verificationId');
        setState(() => _loading = false);
      },
    );
  }

  Future<void> _promptForPasswordAndLogin(String local10) async {
    final TextEditingController _pw = TextEditingController();

    print('DEBUG: entering _promptForPasswordAndLogin for $local10');

    final confirmed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (ctx) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
          backgroundColor: whiteColor,
          insetPadding:
          const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0),
          child: Padding(
            padding:
            const EdgeInsets.symmetric(horizontal: 18.0, vertical: 18.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  getTranslate(context, 'login.enter_password_after_otp') ??
                      'Enter password to continue',
                  style: semibold18Primary,
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                Container(
                  decoration: BoxDecoration(
                    color: whiteColor,
                    borderRadius: BorderRadius.circular(8),
                    boxShadow: [
                      BoxShadow(
                        color: blackColor.withOpacity(0.05),
                        blurRadius: 6,
                      )
                    ],
                  ),
                  child: TextField(
                    controller: _pw,
                    obscureText: true,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 12,
                      ),
                      hintText: getTranslate(context, 'login.enter_password') ??
                          'Password',
                      hintStyle: medium16Grey,
                    ),
                    style: semibold16Black33,
                  ),
                ),
                const SizedBox(height: 20),
                Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () => Navigator.of(ctx).pop(false),
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 12),
                          decoration: BoxDecoration(
                            color: whiteColor,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: greyColor),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            getTranslate(context, 'common.cancel') ?? 'Cancel',
                            style: semibold16Black33,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          if (_pw.text.trim().isEmpty) {
                            ScaffoldMessenger.of(ctx).showSnackBar(
                              SnackBar(
                                content: Text(
                                  getTranslate(
                                      context, 'login.enter_password'),
                                ),
                              ),
                            );
                            return;
                          }
                          Navigator.of(ctx).pop(true);
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 12),
                          decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            getTranslate(context, 'common.verify') ?? 'Verify',
                            style: semibold18White,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                Align(
                  alignment: Alignment.centerRight,
                  child: TextButton(
                    onPressed: () {
                      Navigator.of(ctx).pop(false);
                      _showSnack(
                        getTranslate(context, 'login.forgot_password') ??
                            'Forgot password - contact admin',
                      );
                    },
                    child: Text(
                      getTranslate(context, 'login.forgot_password') ??
                          'Forgot password?',
                      style: medium14Primary,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );

    print(
      'DEBUG: leaving _promptForPasswordAndLogin for $local10 (dialog returned: $confirmed)',
    );

    if (confirmed == true) {
      final password = _pw.text.trim();
      await _loginWithPasswordForPhone(local10, password);
    }
  }

  Future<void> _loginWithPasswordForPhone(
      String local10,
      String password,
      ) async {
    // Block if T&C not accepted
    if (!_agreedToTerms) {
      _showSnack('Please agree to Terms & Conditions and Privacy Policy.');
      return;
    }

    setState(() => _loading = true);
    try {
      final resp = await http.post(
        Uri.parse('https://rmbferodeunited.in/api/login.php'),
        body: {'phone': local10, 'password': password},
      );
      final Map<String, dynamic> jsonResp = json.decode(resp.body);
      if (_isSuccessResponse(jsonResp)) {
        final user = jsonResp['user'] ?? jsonResp;
        print('DEBUG: loginWithPasswordForPhone success -> $user');
        await _saveUserToPrefs(user);
        await _sendFirebaseTokenToServer(local10);
        _goToBottomBar();
      } else {
        final msg = jsonResp['message']?.toString() ?? 'Login failed';
        print(
          'DEBUG: loginWithPasswordForPhone backend failure -> $msg | resp: ${resp.body}',
        );
        _showSnack(msg);
      }
    } catch (e, st) {
      print('DEBUG: loginWithPasswordForPhone exception -> $e');
      print(st);
      _showSnack('Network error: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  // --------------------------
  // Save / token
  // --------------------------
  Future<void> _saveUserToPrefs(dynamic user) async {
    final prefs = await SharedPreferences.getInstance();

    await prefs.setString('name', user['name']?.toString() ?? '');
    await prefs.setString('positions', user['positions']?.toString() ?? '');
    await prefs.setString('rid_no', user['rid_no']?.toString() ?? '');
    await prefs.setString('teams', user['teams']?.toString() ?? '');

    // NEW: store photo_image from API response
    await prefs.setString('photo_image', user['photo_image']?.toString() ?? '');

    // NEW: store company_name and business_type from API response
    await prefs.setString('company_name', user['company_name']?.toString() ?? '');
    await prefs.setString(
        'business_type', user['business_type']?.toString() ?? '');

    String local = user['phone']?.toString() ?? _validateAndGetLocal() ?? '';
    local = _local10(local) ?? local;
    await prefs.setString('phone', local);
  }

  Future<void> _sendFirebaseTokenToServer(String local10) async {
    try {
      final token = await FirebaseMessaging.instance.getToken();
      if (token == null) return;
      await http.post(
        Uri.parse('https://rmbferodeunited.in/api/fireuser.php'),
        body: {
          'phone': local10, // only 10-digit
          'firebase_token': token,
        },
      );
    } catch (_) {
      // ignore token network errors
    }
  }

  // --------------------------
  // UI helpers
  // --------------------------
  void _showSnack(String msg) =>
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));

  bool onWillPop() {
    DateTime now = DateTime.now();
    if (backPressTime == null ||
        now.difference(backPressTime!) >= const Duration(seconds: 2)) {
      backPressTime = now;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: blackColor,
          content: Text(
            getTranslate(context, 'exit_app.exit_text'),
            style: semibold15White,
          ),
          behavior: SnackBarBehavior.floating,
          duration: const Duration(milliseconds: 1500),
        ),
      );
      return false;
    } else {
      return true;
    }
  }

  // --------------------------
  // Widgets
  // --------------------------
  Widget loginButton() {
    return GestureDetector(
      onTap: _loading
          ? null
          : () {
        if (_mode == LoginMode.password) {
          _loginWithPassword();
        } else {
          _startPhoneAuth();
        }
      },
      child: Container(
        width: double.maxFinite,
        padding: const EdgeInsets.symmetric(
          horizontal: fixPadding * 2.0,
          vertical: fixPadding * 1.6,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: primaryColor,
          boxShadow: [
            BoxShadow(
              color: primaryColor.withOpacity(0.15),
              blurRadius: 14.0,
              offset: const Offset(0, 6),
            )
          ],
        ),
        alignment: Alignment.center,
        child: _loading
            ? const SizedBox(
          height: 20,
          width: 20,
          child: CircularProgressIndicator(
            color: Colors.white,
            strokeWidth: 2,
          ),
        )
            : Text(
          getTranslate(context, 'login.login'),
          style: semibold18White,
        ),
      ),
    );
  }

  Widget phoneField() {
    return Container(
      width: double.maxFinite,
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.08),
            blurRadius: 14.0,
            offset: const Offset(0, 6),
          )
        ],
      ),
      child: IntlPhoneField(
        controller: _phoneController,
        initialCountryCode: 'IN',
        onCountryChanged: (country) {
          _countryDialCode = country.dialCode ?? '91';
        },
        textAlignVertical: TextAlignVertical.center,
        cursorColor: primaryColor,
        style: semibold16Black33,
        disableLengthCheck: true,
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: getTranslate(context, 'login.enter_mobile_number'),
          hintStyle: medium16Grey,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: fixPadding,
            vertical: fixPadding * 1.2,
          ),
        ),
      ),
    );
  }

  Widget passwordField() {
    return Container(
      width: double.maxFinite,
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: blackColor.withOpacity(0.08),
            blurRadius: 14.0,
            offset: const Offset(0, 6),
          )
        ],
      ),
      child: TextField(
        controller: _passwordController,
        obscureText: true,
        style: semibold16Black33,
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText:
          getTranslate(context, 'login.enter_password') ?? 'Password',
          hintStyle: medium16Grey,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: fixPadding,
            vertical: fixPadding * 1.2,
          ),
        ),
      ),
    );
  }

  Widget verificationText() => Text(
    getTranslate(context, 'login.verification_text'),
    style: medium14Primary,
  );

  // T&C + Privacy checkbox with links (FIXED STYLES)
  Widget termsAndConditionsRow() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Checkbox(
          value: _agreedToTerms,
          activeColor: primaryColor,
          onChanged: (val) {
            setState(() {
              _agreedToTerms = val ?? false;
            });
          },
        ),
        Expanded(
          child: RichText(
            text: TextSpan(
              style: medium14Grey77, // <-- existing style
              children: [
                const TextSpan(text: 'I agree '),
                TextSpan(
                  text: 'Terms & Conditions',
                  style: medium14Primary.copyWith(
                    decoration: TextDecoration.underline,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Navigator.pushNamed(context, '/termsAndCondition');
                    },
                ),
                const TextSpan(text: ' & '),
                TextSpan(
                  text: 'Privacy Policy',
                  style: medium14Primary.copyWith(
                    decoration: TextDecoration.underline,
                  ),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Navigator.pushNamed(context, '/privacyPolicy');
                    },
                ),
                const TextSpan(text: '.'),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // Become Member button -> /register
  Widget becomeMemberButton() {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, '/register');
      },
      child: Container(
        width: double.maxFinite,
        padding: const EdgeInsets.symmetric(
          horizontal: fixPadding * 2.0,
          vertical: fixPadding * 1.4,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: whiteColor,
          border: Border.all(color: primaryColor, width: 1.2),
          boxShadow: [
            BoxShadow(
              color: blackColor.withOpacity(0.04),
              blurRadius: 10.0,
              offset: const Offset(0, 4),
            )
          ],
        ),
        alignment: Alignment.center,
        child: Text(
          'Become Member',
          style: semibold16Primary,
        ),
      ),
    );
  }

  Widget continueAsGuest() {
    return Align(
      alignment: Alignment.center,
      child: TextButton(
        onPressed: () => _goToBottomBar(),
        child: Text(
          getTranslate(context, 'login.continue_as_guest') ??
              'Continue as Guest',
          style: TextStyle(
            color: primaryColor,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) {
        bool backStatus = onWillPop();
        if (backStatus) exit(0);
      },
      child: Scaffold(
        body: Container(
          height: size.height,
          width: size.width,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/auth/bg.png"),
              fit: BoxFit.fill,
            ),
          ),
          child: ListView(
            padding: const EdgeInsets.all(fixPadding * 2.0),
            physics: const BouncingScrollPhysics(),
            children: [
              heightBox(fixPadding * 7),
              Text(
                getTranslate(context, 'login.LOGIN'),
                style: semibold21Primary,
                textAlign: TextAlign.center,
              ),
              heightBox(fixPadding * 1.5),
              Text(
                getTranslate(context, 'login.please_text'),
                style: medium14Grey77,
                textAlign: TextAlign.center,
              ),
              heightBox(fixPadding * 3),

              // Toggle text on right above phone field
              Row(
                children: [
                  const Expanded(child: SizedBox()),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _mode = _mode == LoginMode.password
                            ? LoginMode.otp
                            : LoginMode.password;
                      });
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      child: Text(
                        _mode == LoginMode.password
                            ? (getTranslate(
                            context, 'login.login_with_otp') ??
                            'Login with OTP')
                            : (getTranslate(
                            context, 'login.login_with_password') ??
                            'Login with Password'),
                        style: TextStyle(
                          color: primaryColor,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),

              heightBox(fixPadding * 1.5),
              phoneField(),
              heightBox(fixPadding * 1.2),
              verificationText(),
              heightBox(fixPadding * 2),

              if (_mode == LoginMode.password) ...[
                passwordField(),
                heightBox(fixPadding * 2),
              ],

              termsAndConditionsRow(),
              heightBox(fixPadding * 2),

              loginButton(),
              heightBox(fixPadding * 2),

              becomeMemberButton(),
              heightBox(fixPadding * 2),

              continueAsGuest(),
              heightBox(fixPadding * 2),
            ],
          ),
        ),
      ),
    );
  }
}
