import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'screens/home_screen.dart';
import 'screens/notification_permission_screen.dart';
import 'screens/edit_profile_screen.dart';
import 'services/auth_service.dart';
import 'services/user_service.dart';
import 'services/app_lifecycle_service.dart';
import 'services/http_service.dart';
import 'dart:convert';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  // Initialize app lifecycle service
  AppLifecycleService.initialize();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Wesal',
      theme: ThemeData(primarySwatch: Colors.blue, fontFamily: 'Roboto'),
      home: SplashScreen(),
      navigatorKey: navigatorKey,
      debugShowCheckedModeBanner: false,
    );
  }
}

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    _checkAuthenticationStatus();
  }

  Future<void> _checkAuthenticationStatus() async {
    await Future.delayed(Duration(milliseconds: 500));

    final isLoggedIn = await AuthService.isLoggedIn();

    if (isLoggedIn) {
      final userResult = await UserService.getCurrentUser();
      if (userResult['success'] == true) {
        final userData = userResult['data'];

        // Check if user needs onboarding (activated = 0)
        if (userData['activated'] == 0) {
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (context) =>
                  EditProfileScreen(userData: userData, isOnboarding: true),
            ),
          );
        } else {
          // Start polling services now that user is logged in and going to main screen
          AppLifecycleService.startAllPolling();
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (context) => HomeScreen()),
          );
        }
      } else {
        await AuthService.logout();
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => LandingPage()),
        );
      }
    } else {
      Navigator.of(
        context,
      ).pushReplacement(MaterialPageRoute(builder: (context) => LandingPage()));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF32B0A5), Color(0xFF4600B9)],
            stops: [0.0, 0.5],
          ),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'وصال',
                style: TextStyle(
                  fontSize: 160,
                  fontWeight: FontWeight.w200,
                  fontFamily: 'Blaka',
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      offset: Offset(2, 2),
                      blurRadius: 4,
                      color: Colors.black.withOpacity(0.3),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 40),
              CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class LandingPage extends StatefulWidget {
  @override
  _LandingPageState createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {
  void _navigateDirectlyToLogin() {
    Navigator.of(
      context,
    ).push(MaterialPageRoute(builder: (context) => SignInPage()));
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false, // Prevent back navigation from landing page
      child: Scaffold(
        body: Stack(
          children: [
            // Background gradient
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color(0xFF32B0A5), // Teal
                    Color(0xFF4600B9), // Purple
                  ],
                  stops: [0.0, 0.5],
                ),
              ),
            ),

            // Main content
            SafeArea(
              child: Column(
                children: [
                  Expanded(
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          // Logo
                          Container(
                            padding: EdgeInsets.all(40),
                            child: Text(
                              'وصال',
                              style: TextStyle(
                                fontSize: 160,
                                fontWeight: FontWeight.w200,
                                fontFamily: 'Blaka',
                                color: Colors.white,
                                shadows: [
                                  Shadow(
                                    offset: Offset(2, 2),
                                    blurRadius: 4,
                                    color: Colors.black.withOpacity(0.3),
                                  ),
                                ],
                              ),
                            ),
                          ),

                          SizedBox(height: 60),

                          // Subtitle
                          Text(
                            'Connections, Made\nEasier!',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 32,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                              height: 1.2,
                            ),
                          ),

                          SizedBox(height: 80),

                          // Get Started Button
                          Container(
                            width: 280,
                            height: 56,
                            child: ElevatedButton(
                              onPressed: _navigateDirectlyToLogin,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Color(0xFF6A4C93),
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(28),
                                ),
                                elevation: 8,
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    'Get Started',
                                    style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  SizedBox(width: 8),
                                  Icon(Icons.arrow_forward, size: 20),
                                ],
                              ),
                            ),
                          ),

                          SizedBox(height: 24),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class SignInPage extends StatefulWidget {
  @override
  _SignInPageState createState() => _SignInPageState();
}

class _SignInPageState extends State<SignInPage> {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = TextEditingController();
  final _passwordController = TextEditingController();
  final _invitationCodeController = TextEditingController();
  final _countryCodeController = TextEditingController(text: '+966');
  bool _isPasswordVisible = false;
  bool _isLoading = false;
  bool _isRegistering = false;
  int _registrationStep = 1; // 1 = invitation code, 2 = phone & password

  void _showHelpBottomSheet() {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (context) => Container(
        padding: EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            SizedBox(height: 24),
            Icon(Icons.contact_support, size: 48, color: Color(0xFF6A4C93)),
            SizedBox(height: 16),
            Text(
              'Need Help?',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            SizedBox(height: 16),
            Text(
              'Registration is by invitation only. If you don\'t have an invitation code, please contact COD/DPSD.',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[700],
                height: 1.4,
              ),
            ),
            SizedBox(height: 24),
            Container(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () => Navigator.pop(context),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Color(0xFF6A4C93),
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: EdgeInsets.symmetric(vertical: 16),
                ),
                child: Text(
                  'Got It',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                ),
              ),
            ),
            SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  Future<void> _checkInvitationCode() async {
    if (_invitationCodeController.text.trim().isEmpty) {
      _showErrorAlert('Please enter your invitation code');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final response = await HttpService.post('/checkInvitation', {
        'code': _invitationCodeController.text.trim().toUpperCase(),
      });

      final data = json.decode(response.body);

      setState(() {
        _isLoading = false;
      });

      if (data['status'] == true &&
          data['data'] != null &&
          data['data']['valid'] == true) {
        // Invitation code is valid, move to step 2
        setState(() {
          _registrationStep = 2;
        });
      } else {
        _showErrorAlert(data['message'] ?? 'Invalid invitation code');
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorAlert('Network error. Please try again.');
    }
  }

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

  void _handleSignIn() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      final phoneNumber =
          _countryCodeController.text.trim() + _phoneController.text.trim();
      final result = await AuthService.login(
        phoneNumber,
        _passwordController.text,
      );

      setState(() {
        _isLoading = false;
      });

      if (result['success'] == true) {
        final userResult = await UserService.getCurrentUser(forceRefresh: true);

        if (userResult['success'] == true) {
          final userData = userResult['data'];

          // Check if user needs onboarding (activated = 0)
          if (userData['activated'] == 0) {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                builder: (context) =>
                    EditProfileScreen(userData: userData, isOnboarding: true),
              ),
            );
          } else {
            // Start polling services now that user is logged in
            AppLifecycleService.startAllPolling();

            Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                builder: (context) => NotificationPermissionScreen(),
              ),
            );
          }
        } else {
          _showErrorAlert('Failed to load user data');
        }
      } else {
        _showErrorAlert(result['message'] ?? 'Login failed');
      }
    }
  }

  void _handleRegister() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      try {
        final phoneNumber =
            _countryCodeController.text.trim() + _phoneController.text.trim();

        final response = await HttpService.post('/register', {
          'code': _invitationCodeController.text.trim().toUpperCase(),
          'phoneNumber': phoneNumber,
          'password': _passwordController.text,
        });

        final data = json.decode(response.body);

        setState(() {
          _isLoading = false;
        });

        if (data['status'] == true && data['data'] != null) {
          // Registration successful, save token and navigate
          final token = data['data']['token'];
          if (token != null) {
            await AuthService.saveToken(token);

            final userResult = await UserService.getCurrentUser(
              forceRefresh: true,
            );
            if (userResult['success'] == true) {
              final userData = userResult['data'];

              // Check if user needs onboarding (activated = false)
              if (userData['activated'] == false) {
                Navigator.of(context).pushReplacement(
                  MaterialPageRoute(
                    builder: (context) => EditProfileScreen(
                      userData: userData,
                      isOnboarding: true,
                    ),
                  ),
                );
              } else {
                AppLifecycleService.startAllPolling();
                Navigator.of(context).pushReplacement(
                  MaterialPageRoute(
                    builder: (context) => NotificationPermissionScreen(),
                  ),
                );
              }
            } else {
              _showErrorAlert(
                'Registration successful but failed to load user data',
              );
            }
          } else {
            _showErrorAlert('Registration successful but no token received');
          }
        } else {
          _showErrorAlert(data['message'] ?? 'Registration failed');
        }
      } catch (e) {
        setState(() {
          _isLoading = false;
        });
        _showErrorAlert('Network error. Please try again.');
      }
    }
  }

  void _showErrorAlert(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(_isRegistering ? 'Registration' : 'Login Failed'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('OK', style: TextStyle(color: Color(0xFF6A4C93))),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false, // Prevent back navigation from sign in page
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFF32B0A5), Color(0xFF4600B9)],
              stops: [0.0, 0.5],
            ),
          ),
          child: SafeArea(
            child: Column(
              children: [
                // App bar
                Padding(
                  padding: EdgeInsets.all(16),
                  child: Row(
                    children: [
                      IconButton(
                        onPressed: () => Navigator.of(context).pop(),
                        icon: Icon(Icons.arrow_back, color: Colors.white),
                      ),
                      Text(
                        _isRegistering ? 'Register' : 'Sign In',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),

                // Content
                Expanded(
                  child: SingleChildScrollView(
                    child: Container(
                      margin: EdgeInsets.all(16),
                      padding: EdgeInsets.all(24),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 20,
                            offset: Offset(0, 5),
                          ),
                        ],
                      ),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            SizedBox(height: 20),

                            // Logo
                            Center(
                              child: Text(
                                'وصال',
                                style: TextStyle(
                                  fontSize: 48,
                                  fontWeight: FontWeight.w200,
                                  fontFamily: 'Blaka',
                                  color: Color(0xFF6A4C93),
                                ),
                              ),
                            ),

                            SizedBox(height: 40),

                            // Welcome text
                            Text(
                              _isRegistering
                                  ? 'Create Account'
                                  : 'Welcome Back!',
                              style: TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                                color: Colors.black87,
                              ),
                              textAlign: TextAlign.center,
                            ),

                            SizedBox(height: 8),

                            Text(
                              _isRegistering
                                  ? 'Join with an invitation code to connect\nwith your colleagues!'
                                  : 'Sign in to socialize with your colleagues\nand transform your social life!',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey[600],
                              ),
                              textAlign: TextAlign.center,
                            ),

                            SizedBox(height: 40),

                            // Registration Step 1: Invitation Code
                            if (_isRegistering && _registrationStep == 1) ...[
                              TextFormField(
                                controller: _invitationCodeController,
                                decoration: InputDecoration(
                                  labelText: 'Invitation Code',
                                  prefixIcon: Icon(
                                    Icons.confirmation_number_outlined,
                                  ),
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide(
                                      color: Color(0xFF6A4C93),
                                    ),
                                  ),
                                  helperText:
                                      '6-character code with letters and numbers',
                                ),
                                maxLength: 6,
                                textCapitalization:
                                    TextCapitalization.characters,
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter your invitation code';
                                  }
                                  if (value.length != 6) {
                                    return 'Invitation code must be 6 characters';
                                  }
                                  if (!RegExp(
                                    r'^[A-Z0-9]{6}$',
                                  ).hasMatch(value)) {
                                    return 'Code must contain only letters and numbers';
                                  }
                                  return null;
                                },
                              ),
                            ],

                            // Login or Registration Step 2: Phone & Password
                            if (!_isRegistering || _registrationStep == 2) ...[
                              // Phone number field with country code input
                              Row(
                                children: [
                                  SizedBox(
                                    width: 100,
                                    child: TextFormField(
                                      controller: _countryCodeController,
                                      keyboardType: TextInputType.phone,
                                      decoration: InputDecoration(
                                        labelText: 'Code',
                                        border: OutlineInputBorder(
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                        ),
                                        focusedBorder: OutlineInputBorder(
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                          borderSide: BorderSide(
                                            color: Color(0xFF6A4C93),
                                          ),
                                        ),
                                      ),
                                      validator: (value) {
                                        if (value == null || value.isEmpty) {
                                          return 'Required';
                                        }
                                        if (!value.startsWith('+')) {
                                          return 'Must start with +';
                                        }
                                        return null;
                                      },
                                    ),
                                  ),
                                  SizedBox(width: 12),
                                  Expanded(
                                    child: TextFormField(
                                      controller: _phoneController,
                                      keyboardType: TextInputType.phone,
                                      decoration: InputDecoration(
                                        labelText: 'Phone Number',
                                        prefixIcon: Icon(Icons.phone_outlined),
                                        border: OutlineInputBorder(
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                        ),
                                        focusedBorder: OutlineInputBorder(
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                          borderSide: BorderSide(
                                            color: Color(0xFF6A4C93),
                                          ),
                                        ),
                                      ),
                                      validator: (value) {
                                        if (value == null || value.isEmpty) {
                                          return 'Please enter your phone number';
                                        }
                                        if (value.length < 8) {
                                          return 'Please enter a valid phone number';
                                        }
                                        return null;
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ],

                            // Password field (only for login or registration step 2)
                            if (!_isRegistering || _registrationStep == 2) ...[
                              SizedBox(height: 20),

                              TextFormField(
                                controller: _passwordController,
                                obscureText: !_isPasswordVisible,
                                decoration: InputDecoration(
                                  labelText: 'Password',
                                  prefixIcon: Icon(Icons.lock_outline),
                                  suffixIcon: IconButton(
                                    icon: Icon(
                                      _isPasswordVisible
                                          ? Icons.visibility_off
                                          : Icons.visibility,
                                    ),
                                    onPressed: () {
                                      setState(() {
                                        _isPasswordVisible =
                                            !_isPasswordVisible;
                                      });
                                    },
                                  ),
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide(
                                      color: Color(0xFF6A4C93),
                                    ),
                                  ),
                                ),
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter your password';
                                  }
                                  if (value.length < 6) {
                                    return 'Password must be at least 6 characters';
                                  }
                                  return null;
                                },
                              ),
                            ],

                            SizedBox(height: 12),

                            // Forgot password (only show for login)
                            if (!_isRegistering)
                              Align(
                                alignment: Alignment.centerRight,
                                child: TextButton(
                                  onPressed: _showHelpBottomSheet,
                                  child: Text(
                                    'Forgot Password?',
                                    style: TextStyle(
                                      color: Color(0xFF6A4C93),
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),

                            SizedBox(height: 30),

                            // Action button based on current state
                            Container(
                              height: 56,
                              child: ElevatedButton(
                                onPressed: _isLoading
                                    ? null
                                    : () {
                                        if (!_isRegistering) {
                                          _handleSignIn();
                                        } else if (_registrationStep == 1) {
                                          _checkInvitationCode();
                                        } else {
                                          _handleRegister();
                                        }
                                      },
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Color(0xFF6A4C93),
                                  foregroundColor: Colors.white,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  elevation: 2,
                                ),
                                child: _isLoading
                                    ? CircularProgressIndicator(
                                        valueColor:
                                            AlwaysStoppedAnimation<Color>(
                                              Colors.white,
                                            ),
                                      )
                                    : Text(
                                        !_isRegistering
                                            ? 'Sign In'
                                            : (_registrationStep == 1
                                                  ? 'Continue'
                                                  : 'Register'),
                                        style: TextStyle(
                                          fontSize: 18,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                              ),
                            ),

                            // Back button for registration step 2
                            if (_isRegistering && _registrationStep == 2) ...[
                              SizedBox(height: 16),
                              Container(
                                height: 56,
                                child: OutlinedButton(
                                  onPressed: () {
                                    setState(() {
                                      _registrationStep = 1;
                                      _phoneController.clear();
                                      _passwordController.clear();
                                    });
                                  },
                                  style: OutlinedButton.styleFrom(
                                    side: BorderSide(color: Color(0xFF6A4C93)),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                  ),
                                  child: Text(
                                    'Back to Invitation Code',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xFF6A4C93),
                                    ),
                                  ),
                                ),
                              ),
                            ],

                            SizedBox(height: 20),

                            // Toggle between login and registration (only show on step 1)
                            if (!_isRegistering || _registrationStep == 1)
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    _isRegistering
                                        ? 'Already have an account? '
                                        : "Don't have an account? ",
                                    style: TextStyle(color: Colors.grey[600]),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        _isRegistering = !_isRegistering;
                                        _registrationStep = 1;
                                        // Clear form when switching modes
                                        _phoneController.clear();
                                        _passwordController.clear();
                                        _invitationCodeController.clear();
                                      });
                                    },
                                    child: Text(
                                      _isRegistering
                                          ? 'Sign In'
                                          : 'Register Now!',
                                      style: TextStyle(
                                        color: Color(0xFF6A4C93),
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                            if (_isRegistering) ...[
                              SizedBox(height: 16),
                              Text(
                                'Registration is only by invitation.\nIf you don\'t have an invite, contact COD/DPSD.',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey[600],
                                  height: 1.3,
                                ),
                              ),
                            ],

                            SizedBox(height: 40),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
