//! Login page component
//!
//! Provides user authentication interface with email/password validation,
//! token storage, and error handling.

use crate::types::{AuthTokenResponse, LoginRequest};

/// Generate HTML for the login page
///
/// # Arguments
///
/// * `error` - Optional error message to display
///
/// # Returns
///
/// HTML string for the login page
pub fn login_page_html(error: Option<&str>) -> String {
    let error_html = if let Some(err) = error {
        format!(
            r#"<div class="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
                <p class="font-medium">Error</p>
                <p class="text-sm">{}</p>
            </div>"#,
            err
        )
    } else {
        String::new()
    };

    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Lifecycle Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
        }}
    </style>
</head>
<body class="bg-gray-50 dark:bg-gray-900">
    <div class="min-h-screen flex items-center justify-center px-4 sm:px-6 lg:px-8">
        <div class="max-w-md w-full space-y-8">
            <div>
                <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900 dark:text-white">
                    Syntaxis Dashboard
                </h2>
                <p class="mt-2 text-center text-sm text-gray-600 dark:text-gray-400">
                    Sign in to manage your projects
                </p>
            </div>

            <div class="bg-white dark:bg-gray-800 py-8 px-4 shadow-lg sm:rounded-lg sm:px-10">
                {}

                <form class="space-y-6" action="/api/auth/login" method="POST">
                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            Email address
                        </label>
                        <div class="mt-1">
                            <input
                                id="email"
                                name="email"
                                type="email"
                                autocomplete="email"
                                required
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 dark:bg-gray-700 dark:text-white focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                                placeholder="you@example.com"
                            />
                        </div>
                    </div>

                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            Password
                        </label>
                        <div class="mt-1">
                            <input
                                id="password"
                                name="password"
                                type="password"
                                autocomplete="current-password"
                                required
                                class="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 dark:bg-gray-700 dark:text-white focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                            />
                        </div>
                    </div>

                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <input
                                id="remember-me"
                                name="remember-me"
                                type="checkbox"
                                class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                            />
                            <label for="remember-me" class="ml-2 block text-sm text-gray-900 dark:text-gray-300">
                                Remember me
                            </label>
                        </div>

                        <div class="text-sm">
                            <a href="/forgot-password" class="font-medium text-blue-600 hover:text-blue-500">
                                Forgot password?
                            </a>
                        </div>
                    </div>

                    <div>
                        <button
                            type="submit"
                            class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition duration-150"
                        >
                            Sign in
                        </button>
                    </div>
                </form>

                <div class="mt-6">
                    <div class="relative">
                        <div class="absolute inset-0 flex items-center">
                            <div class="w-full border-t border-gray-300 dark:border-gray-600"></div>
                        </div>
                        <div class="relative flex justify-center text-sm">
                            <span class="px-2 bg-white dark:bg-gray-800 text-gray-500">
                                Development Mode
                            </span>
                        </div>
                    </div>

                    <div class="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
                        <p>Default credentials for testing:</p>
                        <p class="font-mono mt-1">admin@example.com / admin123</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Check for existing token
        const token = localStorage.getItem('auth_token');
        if (token) {{
            // Redirect to dashboard if already logged in
            window.location.href = '/';
        }}

        // Handle form submission
        document.querySelector('form').addEventListener('submit', async (e) => {{
            e.preventDefault();

            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            try {{
                const response = await fetch('/api/auth/login', {{
                    method: 'POST',
                    headers: {{
                        'Content-Type': 'application/json',
                    }},
                    body: JSON.stringify({{ email, password }}),
                }});

                if (response.ok) {{
                    const data = await response.json();
                    localStorage.setItem('auth_token', data.token);
                    localStorage.setItem('user_id', data.user_id);
                    window.location.href = '/';
                }} else {{
                    const error = await response.json();
                    window.location.href = '/login?error=' + encodeURIComponent(error.error || 'Login failed');
                }}
            }} catch (err) {{
                console.error('Login error:', err);
                window.location.href = '/login?error=' + encodeURIComponent('Network error. Please try again.');
            }}
        }});
    </script>
</body>
</html>"#,
        error_html
    )
}

/// Validate login credentials
///
/// # Arguments
///
/// * `request` - Login request with email and password
///
/// # Returns
///
/// Result containing `AuthTokenResponse` or error message
///
/// # Example
///
/// ```
/// use syntaxis_dashboard::pages::auth::login::validate_login;
/// use syntaxis_dashboard::types::LoginRequest;
///
/// let request = LoginRequest {
///     email: "admin@example.com".to_string(),
///     password: "admin123".to_string(),
/// };
///
/// let result = validate_login(&request);
/// assert!(result.is_ok());
/// ```
pub fn validate_login(request: &LoginRequest) -> Result<AuthTokenResponse, String> {
    // TODO: Replace with actual database validation
    // This is a mock implementation for development
    if request.email == "admin@example.com" && request.password == "admin123" {
        Ok(AuthTokenResponse {
            token: "mock-jwt-token-12345".to_string(),
            expires_in: 3600, // 1 hour
            user_id: "user-001".to_string(),
        })
    } else {
        Err("Invalid email or password".to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_login_page_html_without_error() {
        let html = login_page_html(None);
        assert!(html.contains("Sign in to manage your projects"));
        assert!(!html.contains("Error"));
    }

    #[test]
    fn test_login_page_html_with_error() {
        let html = login_page_html(Some("Invalid credentials"));
        assert!(html.contains("Invalid credentials"));
        assert!(html.contains("bg-red-100"));
    }

    #[test]
    fn test_validate_login_success() {
        let request = LoginRequest {
            email: "admin@example.com".to_string(),
            password: "admin123".to_string(),
        };

        let result = validate_login(&request);
        assert!(result.is_ok());

        let response = result.unwrap();
        assert_eq!(response.user_id, "user-001");
        assert!(response.token.starts_with("mock-jwt-token"));
        assert_eq!(response.expires_in, 3600);
    }

    #[test]
    fn test_validate_login_invalid_email() {
        let request = LoginRequest {
            email: "wrong@example.com".to_string(),
            password: "admin123".to_string(),
        };

        let result = validate_login(&request);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Invalid email or password");
    }

    #[test]
    fn test_validate_login_invalid_password() {
        let request = LoginRequest {
            email: "admin@example.com".to_string(),
            password: "wrongpassword".to_string(),
        };

        let result = validate_login(&request);
        assert!(result.is_err());
    }
}
