use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::card::{Card, CardVariant};
use crate::components::prelude::*;
use crate::api::{get_api_token, AuthError};

#[component]
pub fn ApiSettingsPage() -> impl IntoView {
    let (api_token, set_api_token) = signal(None::<String>);
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal(None::<String>);
    let (copy_success, set_copy_success) = signal(false);
    
    Effect::new(move |_| {
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);
            
            match get_api_token().await {
                Ok(token) => {
                    set_api_token.set(Some(token));
                }
                Err(e) => {
                    log::error!("Failed to fetch API token: {:?}", e);
                    set_error.set(Some(t8s!("Failed to fetch API token").to_string()));
                }
            }
            
            set_loading.set(false);
        });
    });
    
    let handle_copy = move |_: leptos::ev::MouseEvent| {
        if let Some(token) = api_token.get() {
            if let Some(window) = web_sys::window() {
                let navigator = window.navigator();
                let clipboard = navigator.clipboard();
                let _ = clipboard.write_text(&token);
                set_copy_success.set(true);
                
                spawn_local(async move {
                    gloo_timers::future::TimeoutFuture::new(2000).await;
                    set_copy_success.set(false);
                });
            }
        }
    };
    
    let handle_open_docs = move |_: leptos::ev::MouseEvent| {
        if let Some(window) = web_sys::window() {
            let _ = window.open_with_url_and_target(
                "https://www.postman.com/technical-administrator-33862159/vproxy/collection/2l9gs4j/vproxy-api-v3",
                "_blank"
            );
        }
    };
    
    view! {
        <Card 
            variant=CardVariant::L2
            max_width="max-w-sm" 
            padding="p-6" 
            class="w-full"
            id="api-card"
        >
            <div class="flex flex-col gap-4 mb-8" id="api-header">
                <h1 class="text-2xl font-semibold text-[var(--main-light)] tracking-tight" id="api-title">
                    {t8s!("API Settings")}
                </h1>
                <p class="text-base text-[var(--main-light-40)] leading-relaxed" id="api-description">
                    {t8s!("Manage your API access token for integrating with VProxy services. Use this token to authenticate your API requests.")}
                </p>
            </div>
            
            <div class="flex items-center justify-center p-3 mb-8 bg-[var(--other-light-5)] rounded-[14px] min-h-[68px]" id="api-key-container">
                {move || {
                    if loading.get() {
                        view! {
                            <div class="flex items-center gap-3 text-[var(--other-light-60)]" id="loading-indicator">
                                <div class="animate-spin rounded-full h-5 w-5 border-2 border-[var(--other-light-60)] border-t-transparent"></div>
                                <span>{t8s!("Loading API token...")}</span>
                            </div>
                        }.into_any()
                    } else if let Some(error_msg) = error.get() {
                        view! {
                            <div class="text-red-400 text-center" id="error-message">
                                {error_msg}
                            </div>
                        }.into_any()
                    } else if let Some(token) = api_token.get() {
                        view! {
                            <div class="w-full text-base font-normal text-[var(--other-light-60)] leading-relaxed tracking-tight break-all" id="api-key">
                                {token}
                            </div>
                        }.into_any()
                    } else {
                        view! {
                            <div class="text-[var(--main-light-40)] text-center" id="no-token">
                                {t8s!("API token not available")}
                            </div>
                        }.into_any()
                    }
                }}
            </div>
            
            <div class="flex flex-col gap-2" id="button-container">
                <button 
                    class="flex items-center justify-between p-3 gap-2 w-full h-[46px] bg-[var(--main-light-80)] rounded-[14px] font-semibold text-base leading-[22px] tracking-tight text-[var(--main-dark-text)] hover:bg-[var(--main-light)] transition-colors cursor-pointer border-none disabled:opacity-50"
                    on:click=handle_copy
                    prop:disabled=move || loading.get() || api_token.get().is_none()
                    id="copy-button"
                >
                    <span id="copy-button-text">
                        {move || if copy_success.get() {
                            t8s!("Copied!")
                        } else {
                            t8s!("Copy API Token")
                        }}
                    </span>
                </button>
                
                <button 
                    class="flex items-center p-3 gap-2 w-full h-[46px] border border-[var(--main-light-40)] rounded-[14px] font-semibold text-base leading-[22px] tracking-tight text-[var(--main-light-40)] hover:text-[var(--main-light)] hover:border-[var(--main-light)] transition-colors cursor-pointer bg-transparent"
                    on:click=handle_open_docs
                    id="docs-button"
                >
                    <span class="flex-1 text-left" id="docs-button-text">
                        {t8s!("API Documentation")}
                    </span>
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" id="external-link-icon">
                        <path d="M14,3V5H17.59L7.76,14.83L9.17,16.24L19,6.41V10H21V3M19,19H5V5H12V3H5C3.89,3 3,3.9 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V12H19V19Z"/>
                    </svg>
                </button>
            </div>
        </Card>
    }
}
