use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::hooks::use_navigate;
use crate::components::input::CustomInput;
use crate::components::card::{Card, CardContainer, CardHeader, CardContent, CardVariant};
use crate::components::button::{SecondaryLinkButton, PrimaryButton};
use crate::auth::use_auth;
use crate::api::{signin, AuthError};
use crate::{log_component, log_user_action, log_api};
use crate::components::prelude::*;

#[component]
pub fn LoginPage() -> impl IntoView {
    log_component!(created, "LoginPage");
    
    let auth = use_auth();
    let navigate = use_navigate();
    
    {
        let navigate_clone = navigate.clone();
        Effect::new(move |_| {
            if auth.is_authenticated.get() {
                navigate_clone(t8s!("/en/profile"), Default::default());
            }
        });
    }
    
    let (username, set_username) = signal(String::new());
    let (password, set_password) = signal(String::new());
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal::<Option<String>>(None);
    let (show_password, set_show_password) = signal(false);

    let en_profile = t8s!("/en/profile");
    let error_401 = t8s!("Invalid username or password. Please check your credentials and try again.");
    let error_403 = t8s!("Invalid username or password. Please check your credentials and try again.");;
    let error_404 = t8s!("User not found. Please check your username and try again.");
    let error_422 = t8s!("Invalid data provided. Please check your input and try again.");
    let error_500 = t8s!("A server error occurred. Please try again later.");
    let error_503 = t8s!("Service temporarily unavailable. Please try again later.");
    let error_invalid = t8s!("Invalid username or password. Please check your credentials and try again.");
    let error_unexpected = t8s!("An unexpected error occurred. Please try again.");
    let error_network = t8s!("Network error. Please check your connection and try again.");
    let error_fetch = t8s!("Failed to fetch user profile. Please try again.");

    view! {
        <CardContainer id="login-page-container">
            <Card variant=CardVariant::Auth class="w-full" id="login-card">
                <CardHeader variant=CardVariant::Auth id="login-header">
                    {t8s!("Login")}
                </CardHeader>
                
                <CardContent id="login-content">
                    <form class="flex flex-col gap-5" id="login-form" on:submit=move |ev| {
                        ev.prevent_default();
                        
                        let username_val = username.get();
                        let password_val = password.get();
                        
                        if username_val.trim().is_empty() || password_val.trim().is_empty() {
                            set_error.set(Some(t8s!("Please fill in all fields").to_string()));
                            return;
                        }
                        
                        set_loading.set(true);
                        set_error.set(None);
                        
                        let auth_clone = auth.clone();
                        let navigate_clone = navigate.clone();

                        spawn_local(async move {
                            log_api!(request, "signin");
                            
                            match signin(username_val, password_val).await {
                                Ok((token, profile)) => {
                                    log_user_action!("login_success", "LoginPage");
                                    auth_clone.login(token, profile);
                                    navigate_clone(en_profile, Default::default());
                                }
                                Err(e) => {
                                    log_api!(error, "signin", &format!("Login failed: {}", e));

                                    let error_message = match e {
                                        AuthError::HttpError { status, message } => {
                                            match status {
                                                401 => error_401,
                                                403 => error_403,
                                                404 => error_404,
                                                422 => error_422,
                                                500 => error_500,
                                                503 => error_503,
                                                _ => {
                                                    if message.contains("invalid") || message.contains("credentials") {
                                                        error_invalid
                                                    } else {
                                                        error_unexpected
                                                    }
                                                }
                                            }
                                        },
                                        AuthError::NetworkError(_) => error_network,
                                        AuthError::InvalidCredentials => error_invalid,
                                        AuthError::ProfileFetchError => error_fetch,
                                        AuthError::Other(msg) => {
                                            if msg.contains("invalid") || msg.contains("credentials") || msg.contains("password") {
                                                error_invalid
                                            } else {
                                                error_unexpected
                                            }
                                        }
                                    };

                                    set_error.set(Some(error_message.to_string()));
                                }
                            }
                            
                            set_loading.set(false);
                        });
                    }>
                        <div class="flex flex-col" id="username-field-container">
                            <CustomInput
                                placeholder=t8s!("Enter login or email")
                                input_type="text".to_string()
                                value=username
                                on_change=set_username
                                disabled=loading
                            />
                        </div>
                        
                        <div class="flex flex-col" id="password-field-container">
                            {move || if show_password.get() {
                                view! {
                                    <CustomInput
                                        placeholder=t8s!("Enter password")
                                        input_type="text".to_string()
                                        value=password
                                        on_change=set_password
                                        disabled=loading
                                        show_icon=true
                                        icon_type="eye".to_string()
                                        on_icon_click=Box::new(move || {
                                            set_show_password.update(|show| *show = !*show);
                                            log_user_action!("password_visibility_toggle", "LoginPage");
                                        })
                                    />
                                }
                            } else {
                                view! {
                                    <CustomInput
                                        placeholder=t8s!("Enter password")
                                        input_type="password".to_string()
                                        value=password
                                        on_change=set_password
                                        disabled=loading
                                        show_icon=true
                                        icon_type="eye".to_string()
                                        on_icon_click=Box::new(move || {
                                            set_show_password.update(|show| *show = !*show);
                                            log_user_action!("password_visibility_toggle", "LoginPage");
                                        })
                                    />
                                }
                            }}
                        </div>
                        
                        {move || error.get().map(|err| view! {
                            <div class="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-[10px] text-red-400 text-sm" id="login-error">
                                {err}
                            </div>
                        })}
                        
                        <div class="text-center my-[10px] space-y-2" id="auth-links-container">
                            <div id="register-link-container">
                                <span class="text-[var(--text-muted)] text-sm">
                                    {t8r!("No account?")}{" "}
                                    <a href=t8r!("/en/register")().get() id="register-link" class="no-underline font-medium transition-colors text-[var(--text-primary)] duration-300 hover:text-[var(--accent-primary-gradient-gradient)] hover:underline">{t8s!("Register")}</a>
                                </span>
                            </div>
                            
                            <div id="forgot-password-link-container">
                                <a href=t8r!("/en/forgot-password")().get() id="forgot-password-link" class="text-sm text-[var(--text-muted)] hover:text-[var(--accent-primary-gradient-gradient)] transition-colors duration-300">
                                    {t8s!("Forgot your password?")}
                                </a>
                            </div>
                        </div>
                        
                        <PrimaryButton 
                            button_type="submit".to_string()
                            id="login-submit-btn"
                            disabled=loading.into()
                        >
                            {move || if loading.get() { t8s!("Signing in...") } else { t8s!("Sign in") }}
                        </PrimaryButton>
                        
                        <div class="mt-5 text-center" id="telegram-login-container">
                            <SecondaryLinkButton 
                                href=t8r!("/en/telegram-login")().get()
                                id="telegram-login-btn"
                            >
                                {t8s!("Login with Telegram")}
                            </SecondaryLinkButton>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </CardContainer>
    }
}
