use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::prelude::*;
use crate::components::card::{Card, CardVariant};
use crate::components::dropdown::Dropdown;
use crate::auth::use_auth;
use crate::api::{is_password_exists, change_account_password, reset_proxy_password, AuthError};
use rust_shared::repository::model::{PoolType, Profile};
use strum::IntoEnumIterator;
use crate::utils::pool_utils::get_available_pools;  

#[component]
pub fn ChangePasswordPage() -> impl IntoView {
    let auth = use_auth();
    
    let (old_password, set_old_password) = signal(String::new());
    let (new_password, set_new_password) = signal(String::new());
    let (has_password, set_has_password) = signal(false);
    let (loading, set_loading) = signal(false);
    
    let (selected_pool, set_selected_pool) = signal(PoolType::Residential);
    let (current_proxy_password, set_current_proxy_password) = signal(String::new());
    let (proxy_loading, set_proxy_loading) = signal(false);
    
    let profile = move || auth.get_profile();
    let available_pools = {
        let profile = profile.clone();
        move || {
            if let Some(profile) = profile() {
                get_available_pools(&profile)
            } else {
                vec![]
            }
        }
    };

    Effect::new(move |_| {
        spawn_local(async move {
            match is_password_exists().await {
                Ok(exists) => set_has_password.set(exists),
                Err(e) => log::error!("Failed to check password existence: {:?}", e),
            }
        });
    });
    
    {
        let profile = profile.clone();
        Effect::new(move |_| {
            let pool = selected_pool.get();
            if let Some(profile) = profile() {
                let password = get_pool_password(&profile, &pool);
                set_current_proxy_password.set(password);
            }
        });
    }
    
    let handle_account_password_change = move |_| {
        let old_pwd = old_password.get();
        let new_pwd = new_password.get();
        let has_pwd = has_password.get();
        
        if new_pwd.trim().is_empty() {
            log::error!("New password cannot be empty");
            return;
        }
        
        if has_pwd && old_pwd.trim().is_empty() {
            log::error!("Old password is required");
            return;
        }
        
        set_loading.set(true);
        
        spawn_local(async move {
            let old_password_opt = if has_pwd && !old_pwd.trim().is_empty() {
                Some(old_pwd)
            } else {
                None
            };
            
            match change_account_password(old_password_opt, new_pwd).await {
                Ok(_) => {
                    log::info!("Password changed successfully");
                    set_old_password.set(String::new());
                    set_new_password.set(String::new());
                    
                    match is_password_exists().await {
                        Ok(exists) => set_has_password.set(exists),
                        Err(e) => log::error!("Failed to re-check password existence: {:?}", e),
                    }
                }
                Err(e) => {
                    log::error!("Failed to change password: {:?}", e);
                }
            }
            set_loading.set(false);
        });
    };
    
    let handle_proxy_password_reset = move |_| {
        let pool = selected_pool.get();
        set_proxy_loading.set(true);
        
        spawn_local(async move {
            match reset_proxy_password(pool).await {
                Ok(new_password) => {
                    log::info!("Proxy password reset successfully");
                    set_current_proxy_password.set(new_password);
                }
                Err(e) => {
                    log::error!("Failed to reset proxy password: {:?}", e);
                }
            }
            set_proxy_loading.set(false);
        });
    };
    
    let handle_copy_password = move |_| {
        let password = current_proxy_password.get();
        if !password.is_empty() {
            log::info!("Copying password to clipboard: {}", password);
        }
    };
    
    view! {
        <Card 
            variant=CardVariant::L2
            max_width="max-w-md" 
            padding="p-4" 
            class="w-full"
            id="change-password-card"
        >
            {move || {
                let pools = available_pools();
                if !pools.is_empty() {
                    view! {
                        <div class="flex flex-col gap-3 mb-6" id="proxy-password-container">
                            <h3 
                                class="text-xs font-bold uppercase tracking-tight text-[var(--main-light-40)]"
                                id="proxy-password-label"
                            >
                                {t8s!("Proxy Password")}
                            </h3>
                            
                            <div class="flex flex-col gap-3" id="proxy-password-fields">
                    <div 
                        class="flex justify-between items-center p-3.5 gap-2 h-[46px] rounded-[10px]"
                        style="background: var(--other-light-5);"
                        id="proxy-password-display"
                    >
                        <input 
                            type="text"
                            class="flex-1 bg-transparent border-none outline-none text-base font-semibold text-[var(--main-light)] placeholder-[var(--main-light-40)]"
                            prop:value=move || current_proxy_password.get()
                            readonly
                            placeholder="No password"
                            id="proxy-password-input"
                        />
                        <button 
                            class="w-5 h-5 flex items-center justify-center text-[var(--main-light-40)] hover:text-[var(--main-light)] transition-colors"
                            on:click=handle_copy_password
                            id="copy-password-button"
                        >
                            <svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8.25 8.25V6.41667C8.25 5.63602 8.25 5.2457 8.3829 4.94605C8.50097 4.68486 8.68486 4.50097 8.94605 4.3829C9.2457 4.25 9.63602 4.25 10.4167 4.25H15.5833C16.364 4.25 16.7543 4.25 17.054 4.3829C17.3151 4.50097 17.499 4.68486 17.6171 4.94605C17.75 5.2457 17.75 5.63602 17.75 6.41667V11.5833C17.75 12.364 17.75 12.7543 17.6171 13.054C17.499 13.3151 17.3151 13.499 17.054 13.6171C16.7543 13.75 16.364 13.75 15.5833 13.75H13.75M6.41667 17.75H11.5833C12.364 17.75 12.7543 17.75 13.054 17.6171C13.3151 17.499 13.499 17.3151 13.6171 17.054C13.75 16.7543 13.75 16.364 13.75 15.5833V10.4167C13.75 9.63602 13.75 9.2457 13.6171 8.94605C13.499 8.68486 13.3151 8.50097 13.054 8.3829C12.7543 8.25 12.364 8.25 11.5833 8.25H6.41667C5.63602 8.25 5.2457 8.25 4.94605 8.3829C4.68486 8.50097 4.50097 8.68486 4.3829 8.94605C4.25 9.2457 4.25 9.63602 4.25 10.4167V15.5833C4.25 16.364 4.25 16.7543 4.3829 17.054C4.50097 17.3151 4.68486 17.499 4.94605 17.6171C5.2457 17.75 5.63602 17.75 6.41667 17.75Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                        </button>
                    </div>
                    
                    <div class="flex justify-between items-center gap-2" id="proxy-password-controls">
                        <div class="flex-1">
                            <Dropdown
                                selected=selected_pool
                                options={
                                    let available_pools = available_pools.clone();
                                    move || available_pools()
                                }
                                on_change=Callback::new(move |pool| set_selected_pool.set(pool))
                                display_fn=get_pool_display_name
                                id="pool-dropdown"
                            />
                        </div>
                        
                        <button 
                            class="px-3 py-3 h-[46px] rounded-[14px] border border-[var(--main-light-40)] bg-transparent text-base font-semibold text-[var(--main-light-40)] hover:text-[var(--main-light)] hover:border-[var(--main-light)] transition-colors disabled:opacity-50 inline-flex items-center"
                            on:click=handle_proxy_password_reset
                            disabled={
                                let available_pools = available_pools.clone();
                                move || proxy_loading.get() || available_pools().is_empty()
                            }
                            id="reset-proxy-password-button"
                        >
                            {move || if proxy_loading.get() { t8s!("Resetting...") } else { t8s!("Reset") }}
                        </button>
                    </div>
                </div>
            </div>
                        }.into_any()
                    } else {
                        view! {}.into_any()
                    }
                }}
            
            <div class="flex flex-col gap-3" id="account-password-container">
                <h3 
                    class="text-xs font-bold uppercase tracking-tight text-[var(--main-light-40)]"
                    id="account-password-label"
                >
                    {t8s!("Account Password")}
                </h3>
                
                <div class="flex flex-col gap-3" id="account-password-fields">
                    {move || has_password.get().then(|| view! {
                        <div 
                            class="flex justify-between items-center p-3.5 gap-2 h-[46px] rounded-[10px]"
                            style="background: var(--other-light-5);"
                            id="old-password-input-container"
                        >
                            <input 
                                type="password"
                                class="flex-1 bg-transparent border-none outline-none text-base font-semibold text-[var(--main-light)] placeholder-[var(--main-light-40)]"
                                placeholder=t8s!("Old Password")
                                prop:value=move || old_password.get()
                                on:input=move |ev| set_old_password.set(event_target_value(&ev))
                                id="old-password-input"
                            />
                        </div>
                    })}
                    
                    <div 
                        class="flex justify-between items-center p-3.5 gap-2 h-[46px] rounded-[10px]"
                        style="background: var(--other-light-5);"
                        id="new-password-input-container"
                    >
                        <input 
                            type="password"
                            class="flex-1 bg-transparent border-none outline-none text-base font-semibold text-[var(--main-light)] placeholder-[var(--main-light-40)]"
                            placeholder=t8s!("New Password")
                            prop:value=move || new_password.get()
                            on:input=move |ev| set_new_password.set(event_target_value(&ev))
                            id="new-password-input"
                        />
                    </div>
                    
                    <button 
                        class="flex justify-between items-center p-3 gap-2 h-[46px] rounded-[14px] border border-[var(--main-light-40)] bg-transparent text-base font-semibold text-[var(--main-light-40)] hover:text-[var(--main-light)] hover:border-[var(--main-light)] transition-colors disabled:opacity-50"
                        on:click=handle_account_password_change
                        disabled=move || loading.get()
                        id="change-password-button"
                    >
                        <span id="change-password-button-text">
                            {move || if loading.get() { t8s!("Changing...") } else { t8s!("Change Password") }}
                        </span>
                    </button>
                </div>
                
                {move || (!has_password.get()).then(|| view! {
                    <div 
                        class="mt-3 p-3 rounded-lg text-sm text-[var(--main-light-40)]"
                        style="background: var(--other-light-5);"
                        id="no-password-warning"
                    >
                        {t8s!("No account password is currently set. Setting a password will secure your account.")}
                    </div>
                })}
            </div>
        </Card>
    }
}


fn get_pool_password(profile: &Profile, pool: &PoolType) -> String {
    profile.pools
        .get(pool)
        .map(|pool_data| pool_data.get_pool_info().password.clone())
        .flatten()
        .unwrap_or_default()
}

fn get_pool_display_name(pool: &PoolType) -> String {
    match pool {
        PoolType::Residential => "Residential",
        PoolType::Datacenter => "Datacenter",
        PoolType::ResidentialPremium => "Residential Premium",
        PoolType::Mobile => "Mobile",
    }.to_string()
}
