import 'package:flutter/material.dart';
import '../utils/text_utils.dart';
import 'home.dart';

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

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

// State class for LoginScreen, with animation support for flipping forms
class _LoginScreenState extends State<LoginScreen>
    with SingleTickerProviderStateMixin {
  bool isDarkMode = false; // Tracks dark mode state
  bool isRemembered = false; // Tracks "Remember Me" checkbox
  bool isLogin = true; // Tracks if login or register form is shown

  // Controllers for email and password input fields
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  // Hardcoded credentials, updated on registration or password reset
  String _correctEmail = 'Amazons@tech.com';
  String _correctPassword = '12345';

  // Animation controller and animation for flipping between forms
  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    // Initialize animation controller for flip effect
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    );
    // Tween for flip animation
    _animation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    // Dispose controllers to free resources
    _animationController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  // Login logic: checks credentials and navigates to HomePage if correct
  void _login() {
    if (_emailController.text == _correctEmail &&
        _passwordController.text == _correctPassword) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => HomePage(email: _emailController.text), // Go to HomePage
        ),
      );
    } else {
      // Show error if credentials are wrong
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('Invalid credentials')));
    }
  }

  // Registration logic: updates hardcoded credentials and flips back to login
  void _register() {
    if (_emailController.text.isNotEmpty &&
        _passwordController.text.isNotEmpty) {
      setState(() {
        _correctEmail = _emailController.text; // Update email
        _correctPassword = _passwordController.text; // Update password
        isLogin = true; // Switch to login form
      });
      _animationController.reverse(); // Animate back to login
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Registration successful! Please login')),
      );
    }
  }

  // Password reset logic: updates the hardcoded password
  void _resetPassword(String newPassword) {
    setState(() {
      _correctPassword = newPassword; // Update password
    });
    Navigator.pop(context); // Close dialog
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Password updated successfully!')),
    );
  }

  // Shows a dialog to enter a new password for reset
  void _showResetPasswordDialog() {
    final TextEditingController newPasswordController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          'Reset Password',
          style: TextStyle(color: isDarkMode ? Colors.white : Colors.black),
        ),
        content: SizedBox(
          height: 100,
          child: Column(
            children: [
              TextFormField(
                controller: newPasswordController, // Controller for new password
                obscureText: true, // Hide input
                decoration: InputDecoration(
                  labelText: 'New Password',
                  labelStyle: TextStyle(
                    color: isDarkMode ? Colors.white70 : Colors.black54,
                  ),
                  border: OutlineInputBorder(),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: isDarkMode ? Colors.white70 : Colors.black54,
                    ),
                  ),
                ),
                style: TextStyle(
                  color: isDarkMode ? Colors.white : Colors.black,
                ),
              ),
            ],
          ),
        ),
        backgroundColor: isDarkMode ? Colors.grey[900] : Colors.white,
        actions: [
          // Cancel button
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: TextStyle(
                color: isDarkMode ? Colors.white70 : Colors.black54,
              ),
            ),
          ),
          // Update button
          TextButton(
            onPressed: () {
              if (newPasswordController.text.isNotEmpty) {
                _resetPassword(newPasswordController.text); // Update password
              }
            },
            child: Text(
              'Update',
              style: TextStyle(
                color: const Color(0xFFC76723),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // Login form widget
  Widget _buildLoginForm() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 20), // Spacer
        Center(
          child: SizedBox(
            height: 150,
            width: 200,
            child: Image.asset('assets/logo.png', fit: BoxFit.contain), // Logo
          ),
        ),
        const SizedBox(height: 4),
        Center(
          child: TextUtil(
            text: "Login",
            weight: true,
            size: 30,
            color: isDarkMode ? Colors.white : Colors.black,
          ),
        ),
        const SizedBox(height: 20),
        TextUtil(
          text: "Email",
          color: isDarkMode ? Colors.white : Colors.black,
        ),
        Container(
          height: 35,
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: isDarkMode ? Colors.white : Colors.black,
              ),
            ),
          ),
          child: TextFormField(
            controller: _emailController, // Email input
            style: TextStyle(color: isDarkMode ? Colors.white : Colors.black),
            decoration: InputDecoration(
              suffixIcon: Icon(
                Icons.mail,
                color: isDarkMode ? Colors.white : Colors.black,
              ),
              border: InputBorder.none,
            ),
          ),
        ),
        const SizedBox(height: 20),
        TextUtil(
          text: "Password",
          color: isDarkMode ? Colors.white : Colors.black,
        ),
        Container(
          height: 35,
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: isDarkMode ? Colors.white : Colors.black,
              ),
            ),
          ),
          child: TextFormField(
            controller: _passwordController, // Password input
            obscureText: true, // Hide input
            style: TextStyle(color: isDarkMode ? Colors.white : Colors.black),
            decoration: InputDecoration(
              suffixIcon: Icon(
                Icons.lock,
                color: isDarkMode ? Colors.white : Colors.black,
              ),
              border: InputBorder.none,
            ),
          ),
        ),
        const SizedBox(height: 20),
        Row(
          children: [
            // Remember Me checkbox
            TextButton.icon(
              onPressed: () {
                setState(() {
                  isRemembered = !isRemembered;
                });
              },
              icon: Icon(
                isRemembered ? Icons.check_box : Icons.check_box_outline_blank,
                color: isDarkMode ? Colors.white : Colors.black,
                size: 18,
              ),
              label: TextUtil(
                text: "Remember Me",
                size: 12,
                color: isDarkMode ? Colors.white : Colors.black,
              ),
              style: TextButton.styleFrom(padding: EdgeInsets.zero),
            ),
            const Spacer(),
            // Forget password button
            TextButton(
              onPressed: _showResetPasswordDialog, // Show reset dialog
              style: TextButton.styleFrom(padding: EdgeInsets.zero),
              child: TextUtil(
                text: "FORGET PASSWORD",
                size: 12,
                color: isDarkMode ? Colors.white : Colors.black,
              ),
            ),
          ],
        ),
        const SizedBox(height: 20),
        // Login button
        GestureDetector(
          onTap: _login, // Call login logic
          child: Container(
            height: 40,
            width: double.infinity,
            decoration: BoxDecoration(
              color: isDarkMode ? Colors.white : Colors.black,
              borderRadius: BorderRadius.circular(30),
            ),
            alignment: Alignment.center,
            child: TextUtil(
              text: "Log In",
              color: isDarkMode ? Colors.black : Colors.white,
            ),
          ),
        ),
        const SizedBox(height: 20),
        // Switch to register form
        GestureDetector(
          onTap: () {
            setState(() {
              isLogin = false; // Show register form
              _emailController.clear();
              _passwordController.clear();
            });
            _animationController.forward(); // Animate flip
          },
          child: Center(
            child: TextUtil(
              text: "Don't have an account? REGISTER",
              size: 14,
              color: isDarkMode ? Colors.white : Colors.black,
            ),
          ),
        ),
      ],
    );
  }

  // Register form widget (flipped)
  Widget _buildRegisterForm() {
    return Transform(
      transform: Matrix4.identity()..rotateY(3.14159), // Flip effect
      alignment: Alignment.center,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 20),
          Center(
            child: SizedBox(
              height: 150,
              width: 200,
              child: Image.asset('assets/logo.png', fit: BoxFit.contain), // Logo
            ),
          ),
          const SizedBox(height: 20),
          Center(
            child: TextUtil(
              text: "Register",
              weight: true,
              size: 30,
              color: isDarkMode ? Colors.white : Colors.black,
            ),
          ),
          const SizedBox(height: 20),
          TextUtil(
            text: "Email",
            color: isDarkMode ? Colors.white : Colors.black,
          ),
          Container(
            height: 35,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: isDarkMode ? Colors.white : Colors.black,
                ),
              ),
            ),
            child: TextFormField(
              controller: _emailController, // Email input
              style: TextStyle(color: isDarkMode ? Colors.white : Colors.black),
              decoration: InputDecoration(
                suffixIcon: Icon(
                  Icons.mail,
                  color: isDarkMode ? Colors.white : Colors.black,
                ),
                border: InputBorder.none,
              ),
            ),
          ),
          const SizedBox(height: 20),
          TextUtil(
            text: "Password",
            color: isDarkMode ? Colors.white : Colors.black,
          ),
          Container(
            height: 35,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: isDarkMode ? Colors.white : Colors.black,
                ),
              ),
            ),
            child: TextFormField(
              controller: _passwordController, // Password input
              obscureText: true, // Hide input
              style: TextStyle(color: isDarkMode ? Colors.white : Colors.black),
              decoration: InputDecoration(
                suffixIcon: Icon(
                  Icons.lock,
                  color: isDarkMode ? Colors.white : Colors.black,
                ),
                border: InputBorder.none,
              ),
            ),
          ),
          const SizedBox(height: 40),
          // Register button
          GestureDetector(
            onTap: _register, // Call register logic
            child: Container(
              height: 40,
              width: double.infinity,
              decoration: BoxDecoration(
                color: isDarkMode ? Colors.white : Colors.black,
                borderRadius: BorderRadius.circular(30),
              ),
              alignment: Alignment.center,
              child: TextUtil(
                text: "Register Me",
                color: isDarkMode ? Colors.black : Colors.white,
              ),
            ),
          ),
          const SizedBox(height: 20),
          // Switch to login form
          GestureDetector(
            onTap: () {
              setState(() {
                isLogin = true; // Show login form
                _emailController.clear();
                _passwordController.clear();
              });
              _animationController.reverse(); // Animate flip
            },
            child: Center(
              child: TextUtil(
                text: "Already have an account? LOGIN",
                size: 14,
                color: isDarkMode ? Colors.white : Colors.black,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: isDarkMode ? ThemeData.dark() : ThemeData.light(), // Set theme
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color(0xFFC76723), // Custom orange color
          elevation: 0,
          actions: [
            IconButton(
              icon: Icon(
                isDarkMode ? Icons.light_mode : Icons.dark_mode,
                color: Colors.white,
              ),
              onPressed: () {
                setState(() {
                  isDarkMode = !isDarkMode; // Toggle theme
                });
              },
            ),
          ],
        ),
        body: Container(
          height: double.infinity,
          width: double.infinity,
          color: isDarkMode ? const Color.fromARGB(255, 26, 24, 24) : Colors.white, // Background color
          child: Align(
            alignment: Alignment.center,
            child: Container(
              width: double.infinity,
              margin: const EdgeInsets.symmetric(horizontal: 30),
              decoration: BoxDecoration(
                border: Border.all(
                  color: isDarkMode
                      ? const Color(0xFF23272F) // Use a dark blue/grey for dark mode
                      : const Color.fromARGB(136, 71, 69, 69),
                ),
                borderRadius: BorderRadius.circular(15),
                color: isDarkMode
                    ? const Color.fromARGB(137, 132, 129, 129) // Use a dark blue/grey for dark mode
                    : Colors.white70,
              ),
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(25),
                  child: AnimatedBuilder(
                    animation: _animation,
                    builder: (context, child) {
                      // Flip between login and register forms
                      return Transform(
                        transform: Matrix4.identity()
                          ..setEntry(3, 2, 0.001)
                          ..rotateY(3.14159 * _animation.value),
                        alignment: Alignment.center,
                        child: isLogin ? _buildLoginForm() : _buildRegisterForm(),
                      );
                    },
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
