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::{signup, register_with_referral, track_referral_source, AuthError};
use crate::{log_component, log_user_action, log_api};
use crate::components::prelude::*;


#[component]
pub fn RegisterPage() -> impl IntoView {
    log_component!(created, "RegisterPage");
    
    let auth = use_auth();
    let navigate = use_navigate();
    let navigate_for_effect = navigate.clone();
    let navigate_for_form = navigate.clone();
    let navigate_for_message = navigate.clone();
    let referral_context = use_referral_tracking();
    
    Effect::new(move |_| {
        let referral_data = referral_context.referral_data.get();
        if referral_data.referral_code.is_some() || referral_data.admin_referral_code.is_some() {
            spawn_local(async move {
                let _ = track_referral_source(
                    referral_data.referral_code.as_deref(),
                    referral_data.admin_referral_code.as_deref(),
                    None, // utm_source
                    None, // utm_medium
                    None, // utm_campaign
                ).await;
            });
        }
    });
    
    {
        Effect::new(move |_| {
            if auth.is_authenticated.get() {
                navigate_for_effect(t8s!("/en/profile"), Default::default());
            }
        });
    }
    
    let (username, set_username) = signal(String::new());
    let (email, set_email) = signal(String::new());
    let (password, set_password) = signal(String::new());
    let (confirm_password, set_confirm_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 (show_confirm_password, set_show_confirm_password) = signal(false);
    let (show_email_check, set_show_email_check) = signal(false);

    let email_or_username_already_exists_error = t8s!("An account with this email or username already exists. Please try a different email or username.");
    let this_resource_already_exists_error = t8s!("This resource already exists. Please try again.");
    let the_referral_code_you_entered_is_invalid_error = t8s!("The referral code you entered is invalid. Please check the code and try again.");
    let invalid_request_error = t8s!("Invalid request. Please check your input and try again.");
    let invalid_data_provided_error = t8s!("Invalid data provided. Please check your input and try again.");
    let service_temporarily_unavailable_error = t8s!("Service temporarily unavailable. Please try again later.");
    let a_server_error_occurred_error = t8s!("A server error occurred. Please try again later.");
    let an_account_with_this_information_already_exists_error = t8s!("An account with this information already exists. Please try different details.");
    let an_unexpected_error_occurred_error = t8s!("An unexpected error occurred. Please try again.");

    // Error handling function inside component context
    let get_user_friendly_error = move |error: &AuthError| -> String {
        match error {
            AuthError::HttpError { status, message } => {
                match status {
                    409 => {
                        if message.contains("email") || message.contains("username") || message.contains("already exists") {
                            email_or_username_already_exists_error.to_string()
                        } else {
                            this_resource_already_exists_error.to_string()
                        }
                    },
                    400 => {
                        if message.contains("referral") {
                            the_referral_code_you_entered_is_invalid_error.to_string()
                        } else {
                            invalid_request_error.to_string()
                        }
                    },
                    422 => invalid_data_provided_error.to_string(),
                    500 => a_server_error_occurred_error.to_string(),
                    503 => service_temporarily_unavailable_error.to_string(),
                    _ => {
                        if message.contains("already exists") || message.contains("duplicate") {
                            an_account_with_this_information_already_exists_error.to_string()
                        } else {
                            an_unexpected_error_occurred_error.to_string()
                        }
                    }
                }
            },
            AuthError::NetworkError(_) => t8s!("Network error. Please check your connection and try again.").to_string(),
            AuthError::InvalidCredentials => t8s!("Invalid username or password.").to_string(),
            AuthError::ProfileFetchError => t8s!("Failed to fetch user profile. Please try again.").to_string(),
            AuthError::Other(msg) => {
                if msg.contains("PT409") || msg.contains("already exists") || msg.contains("duplicate") {
                    t8s!("An account with this email or username already exists. Please try a different email or username.").to_string()
                } else {
                    t8s!("An unexpected error occurred. Please try again.").to_string()
                }
            }
        }
    };

    let success_message = t8s!("Registration Successful!");
    let email_check_message = t8s!("Please check your email and click the verification link to activate your account.");
    let go_to_login_message = t8s!("Go to Login");
    let profile_url = t8s!("/en/profile");
    let fill_fields_error = t8s!("Please fill in all fields");
    let passwords_do_not_match_error = t8s!("Passwords do not match");
    let password_must_be_at_least_6_characters_long_error = t8s!("Password must be at least 6 characters long");
    let invalid_email_error = t8s!("Please enter a valid email address");
    let username_must_be_at_least_3_characters_long_error = t8s!("Username must be at least 3 characters long");

    view! {
        <CardContainer id="register-page-container">
            <Card variant=CardVariant::Auth class="w-full" id="register-card">
                <CardHeader variant=CardVariant::Auth id="register-header">
                    {t8s!("Registration")}
                </CardHeader>
                
                <CardContent id="register-content">
                    <form class="flex flex-col gap-5" id="register-form" on:submit=move |ev| {
                        ev.prevent_default();
                        
                        let username_val = username.get();
                        let email_val = email.get();
                        let password_val = password.get();
                        let confirm_password_val = confirm_password.get();
                        
                        if username_val.trim().is_empty() || email_val.trim().is_empty() || 
                           password_val.trim().is_empty() || confirm_password_val.trim().is_empty() {
                            set_error.set(Some(fill_fields_error.to_string()));
                            return;
                        }
                        
                        if password_val != confirm_password_val {
                            set_error.set(Some(passwords_do_not_match_error.to_string()));
                            return;
                        }
                        
                        if password_val.len() < 6 {
                            set_error.set(Some(password_must_be_at_least_6_characters_long_error.to_string()));
                            return;
                        }
                        
                        if !email_val.contains('@') {
                            set_error.set(Some(invalid_email_error.to_string()));
                            return;
                        }
                        
                        if username_val.len() < 3 {
                            set_error.set(Some(username_must_be_at_least_3_characters_long_error.to_string()));
                            return;
                        }
                        
                        set_loading.set(true);
                        set_error.set(None);
                        
                        let auth_clone = auth.clone();
                        let referral_data = referral_context.referral_data.get();
                        spawn_local(async move {
                            log_api!(request, "signup");
                            
                            let result = if referral_data.referral_code.is_some() || referral_data.admin_referral_code.is_some() {
                                register_with_referral(
                                    &username_val,
                                    &password_val,
                                    referral_data.referral_code.as_deref(),
                                    referral_data.admin_referral_code.as_deref(),
                                ).await
                            } else {
                                signup(username_val, email_val, password_val).await
                            };
                            
                            match result {
                                Ok(_token) => {
                                    log_user_action!("register_success", "RegisterPage");
                                    // Don't login automatically - user needs to verify email first
                                    set_show_email_check.set(true);
                                }
                                Err(e) => {
                                    log_api!(error, "signup", &format!("Registration failed: {}", e));
                                    set_error.set(Some(get_user_friendly_error(&e)));
                                }
                            }
                            
                            set_loading.set(false);
                        });
                    }>
                        <div class="flex flex-col" id="username-field-container">
                            <CustomInput
                                placeholder=t8s!("Enter username")
                                input_type="text".to_string()
                                value=username
                                on_change=set_username
                                disabled=loading
                            />
                        </div>
                        
                        <div class="flex flex-col" id="email-field-container">
                            <CustomInput
                                placeholder=t8s!("Enter email")
                                input_type="email".to_string()
                                value=email
                                on_change=set_email
                                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", "RegisterPage");
                                        })
                                    />
                                }
                            } 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", "RegisterPage");
                                        })
                                    />
                                }
                            }}
                        </div>
                        
                        <div class="flex flex-col" id="confirm-password-field-container">
                            {move || if show_confirm_password.get() {
                                view! {
                                    <CustomInput
                                        placeholder=t8s!("Confirm password")
                                        input_type="text".to_string()
                                        value=confirm_password
                                        on_change=set_confirm_password
                                        disabled=loading
                                        show_icon=true
                                        icon_type="eye".to_string()
                                        on_icon_click=Box::new(move || {
                                            set_show_confirm_password.update(|show| *show = !*show);
                                            log_user_action!("confirm_password_visibility_toggle", "RegisterPage");
                                        })
                                    />
                                }
                            } else {
                                view! {
                                    <CustomInput
                                        placeholder=t8s!("Confirm password")
                                        input_type="password".to_string()
                                        value=confirm_password
                                        on_change=set_confirm_password
                                        disabled=loading
                                        show_icon=true
                                        icon_type="eye".to_string()
                                        on_icon_click=Box::new(move || {
                                            set_show_confirm_password.update(|show| *show = !*show);
                                            log_user_action!("confirm_password_visibility_toggle", "RegisterPage");
                                        })
                                    />
                                }
                            }}
                        </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="register-error">
                                {err}
                            </div>
                        })}
                        
                        <div class="text-center my-[10px]" id="login-link-container">
                            <span class="text-[var(--text-muted)] text-sm">
                                {t8r!("Already have an account?")}{" "}
                                <a href=t8r!("/en/login")().get() id="login-link" class="text-[var(--text-primary)] no-underline font-medium transition-colors duration-300 hover:text-[var(--accent-primary-gradient-gradient)] hover:underline">{t8r!("Login")}</a>
                            </span>
                        </div>
                        
                        <PrimaryButton 
                            button_type="submit".to_string()
                            id="register-submit-btn"
                            disabled=loading.into()
                        >
                            {move || if loading.get() { t8s!("Registration...") } else { t8s!("Register") }}
                        </PrimaryButton>
                        
                        {move || if show_email_check.get() {
                            let navigate_clone = navigate_for_message.clone();
                            view! {
                                <div class="mt-6 p-4 bg-green-500/10 border border-green-500/30 rounded-[10px] text-center" id="email-check-message">
                                    <div class="text-green-400 text-lg font-semibold mb-2">
                                        {success_message}
                                    </div>
                                    <div class="text-green-300 text-sm mb-4">
                                        {email_check_message}
                                    </div>
                                    <button 
                                        type="button"
                                        class="bg-[var(--btn-secondary-bg)] text-[var(--text-alternative)] border-none rounded-xl py-4 px-5 text-base font-semibold cursor-pointer transition-all duration-300 mt-[10px] hover:bg-[var(--btn-secondary-bg-hover)] hover:-translate-y-px hover:shadow-[0_4px_12px_var(--shadow-darker)] disabled:opacity-50 disabled:cursor-not-allowed"
                                        id="go-to-profile-btn"
                                        on:click=move |_| {
                                            navigate_clone(profile_url, Default::default());
                                        }
                                    >
                                       {go_to_login_message}
                                    </button>
                                </div>
                            }.into_any()
                        } else {
                            view! {}.into_any()
                        }}
                        
                        <div class="mt-5 text-center" id="telegram-register-container">
                            <SecondaryLinkButton 
                                href=t8r!("/en/telegram-register")().get()
                                id="telegram-register-btn"
                            >
                                {t8s!("Register with Telegram")}
                            </SecondaryLinkButton>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </CardContainer>
    }
}
