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::telegram_code_signin;
use crate::{log_component, log_user_action, log_api};
use crate::config::get_telegram_bot_username;
use crate::components::prelude::*;

#[component]
pub fn TelegramSignin() -> impl IntoView {
    log_component!(created, "TelegramSignin");
    
    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 (code, set_code) = signal(String::new());
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal::<Option<String>>(None);
    
    view! {
        <CardContainer id="telegram-signin-page-container">
            <Card variant=CardVariant::Auth class="w-full" id="telegram-signin-card">
                <CardHeader variant=CardVariant::Auth id="telegram-signin-header">
                    {t8s!("Telegram Login")}
                </CardHeader>
                
                <CardContent id="telegram-signin-content">
                    <div class="text-center mb-6" id="telegram-instructions">
                        <p class="text-[var(--text-secondary)] mb-3" id="telegram-instruction-text">
                            {t8s!("Enter the code from the bot")}
                        </p>
                        <div class="text-center text-[var(--text-muted)] text-sm" id="telegram-bot-info">
                            <p id="telegram-bot-instruction">{t8s!("To get the authorization code")}</p>
                            <p id="telegram-bot-link-container">
                                {t8s!("go to")} " "
                                <a 
                                    href=format!("https://t.me/{}", get_telegram_bot_username())
                                    target="_blank" 
                                    rel="noopener noreferrer" 
                                    class="text-[var(--accent-primary-gradient)] hover:text-[var(--accent-primary-gradient-gradient)] transition-colors duration-300"
                                    id="telegram-bot-link"
                                >
                                    {format!("@{}", get_telegram_bot_username())}
                                </a>
                            </p>
                        </div>
                    </div>
                    
                    <form class="flex flex-col gap-5" id="telegram-signin-form" on:submit=move |ev| {
                        ev.prevent_default();
                        
                        let code_val = code.get();
                        
                        if code_val.trim().is_empty() {
                            set_error.set(Some(t8s!("Enter the code from the bot").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, "telegram_code_signin");
                            
                            match telegram_code_signin(code_val).await {
                                Ok((token, profile)) => {
                                    log_user_action!("telegram_login_success", "TelegramSignin");
                                    auth_clone.login(token, profile);
                                    navigate_clone(t8s!("/en/profile"), Default::default());
                                }
                                Err(e) => {
                                    log_api!(error, "telegram_code_signin", &format!("Telegram login failed: {}", e));
                                    set_error.set(Some(e.to_string()));
                                }
                            }
                            
                            set_loading.set(false);
                        });
                    }>
                        <div class="flex flex-col" id="telegram-code-field-container">
                            <CustomInput
                                placeholder=t8s!("Enter code from bot")
                                input_type="text".to_string()
                                value=code
                                on_change=set_code
                                disabled=loading
                            />
                        </div>
                        
                        {move || error.get().map(|err| view! {
                            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mt-2" id="telegram-signin-error">
                                {err}
                            </div>
                        })}
                        
                        <PrimaryButton 
                            button_type="submit".to_string()
                            id="telegram-signin-submit-btn"
                            disabled=loading.into()
                        >
                            {move || if loading.get() { t8s!("Signing in...") } else { t8s!("Sign in") }}
                        </PrimaryButton>
                        
                        <div class="mt-5 text-center" id="back-to-login-container">
                            <SecondaryLinkButton 
                                href=t8r!("/en/login")().get()
                                id="back-to-login-link"
                            >
                                {t8r!("Back to login page")}
                            </SecondaryLinkButton>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </CardContainer>
    }
}
