use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::card::{Card, CardVariant};
use crate::components::prelude::*;
use crate::api::{get_referral_info, AuthError};
use rust_shared::repository::model::ReferralInfo;

#[component]
pub fn ReferralPage() -> impl IntoView {
    let (referral_data, set_referral_data) = signal(None::<ReferralInfo>);
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal(None::<String>);
    let (copy_success_website, set_copy_success_website) = signal(false);
    let (copy_success_telegram, set_copy_success_telegram) = signal(false);
    
    Effect::new(move |_| {
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);
            
            match get_referral_info().await {
                Ok(data) => {
                    set_referral_data.set(Some(data));
                }
                Err(e) => {
                    log::error!("Failed to fetch referral info: {:?}", e);
                    set_error.set(Some(t8s!("Failed to fetch referral information").to_string()));
                }
            }
            
            set_loading.set(false);
        });
    });
    
    let handle_copy_website = move |_: leptos::ev::MouseEvent| {
        if let Some(data) = referral_data.get() {
            copy_to_clipboard(&data.links.website);
            set_copy_success_website.set(true);
            
            spawn_local(async move {
                gloo_timers::future::TimeoutFuture::new(3000).await;
                set_copy_success_website.set(false);
            });
        }
    };
    
    let handle_copy_telegram = move |_: leptos::ev::MouseEvent| {
        if let Some(data) = referral_data.get() {
            copy_to_clipboard(&data.links.telegram);
            set_copy_success_telegram.set(true);
            
            spawn_local(async move {
                gloo_timers::future::TimeoutFuture::new(3000).await;
                set_copy_success_telegram.set(false);
            });
        }
    };
    
    view! {
        <Card 
            variant=CardVariant::L2
            max_width="flex-1" 
            padding="p-3" 
            class="w-full"
            id="referral-card"
        >
            {move || {
                if loading.get() {
                    view! {
                        <div class="flex flex-col items-center justify-center h-96 gap-4" id="loading-container">
                            <div class="animate-spin rounded-full h-12 w-12 border-2 border-[var(--main-light-40)] border-t-transparent"></div>
                            <span class="text-[var(--main-light-40)]">{t8s!("Loading referral data...")}</span>
                        </div>
                    }.into_any()
                } else if let Some(error_msg) = error.get() {
                    view! {
                        <div class="flex flex-col items-center justify-center h-96 gap-4" id="error-container">
                            <div class="text-red-400 text-center text-lg" id="error-message">
                                {error_msg}
                            </div>
                        </div>
                    }.into_any()
                } else if let Some(data) = referral_data.get() {
                    let balance: f64 = data.balance.parse().unwrap_or(0.0);
                    let referrals: i32 = data.count.parse().unwrap_or(0);
                    let percent: f64 = data.percent.parse().unwrap_or(0.0);
                    
                    view! {
                        <div class="flex flex-col items-center gap-12 py-8" id="referral-container">
                            <div class="flex flex-col gap-2 w-80" id="stats-container">
                                <div class="flex items-center justify-between p-4 bg-[var(--other-light-5)] rounded-[14px] h-[52px]" id="balance-row">
                                    <div class="flex items-center gap-2" id="balance-container">
                                        <svg width="22" height="22" viewBox="0 0 24 24" fill="var(--main-light-40)" id="balance-icon">
                                            <path d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4M12,6A6,6 0 0,0 6,12A6,6 0 0,0 12,18A6,6 0 0,0 18,12A6,6 0 0,0 12,6M12,8A4,4 0 0,1 16,12A4,4 0 0,1 12,16A4,4 0 0,1 8,12A4,4 0 0,1 12,8Z"/>
                                        </svg>
                                        <span class="text-lg font-semibold text-[var(--main-light-40)] leading-6 tracking-tight" id="balance-label">
                                            {t8s!("Balance")}
                                        </span>
                                    </div>
                                    <span class="text-lg font-semibold text-[var(--main-light)] leading-6 tracking-tight" id="balance-value">
                                        {format!("${:.2}", balance)}
                                    </span>
                                </div>
                                
                                <div class="flex items-center justify-between p-4 bg-[var(--other-light-5)] rounded-[14px] h-[52px]" id="referrals-row">
                                    <div class="flex items-center gap-2" id="referrals-container">
                                        <svg width="22" height="22" viewBox="0 0 24 24" fill="var(--main-light-40)" id="referrals-icon">
                                            <path d="M16,4C16.88,4 17.67,4.38 18.18,5C18.69,4.38 19.48,4 20.36,4C21.8,4 23,5.2 23,6.64C23,8.08 21.8,9.28 20.36,9.28C19.48,9.28 18.69,8.9 18.18,8.28C17.67,8.9 16.88,9.28 16,9.28C14.56,9.28 13.36,8.08 13.36,6.64C13.36,5.2 14.56,4 16,4M16,10.92C16.88,10.92 17.67,11.3 18.18,11.92C18.69,11.3 19.48,10.92 20.36,10.92C21.8,10.92 23,12.12 23,13.56C23,15 21.8,16.2 20.36,16.2C19.48,16.2 18.69,15.82 18.18,15.2C17.67,15.82 16.88,16.2 16,16.2C14.56,16.2 13.36,15 13.36,13.56C13.36,12.12 14.56,10.92 16,10.92M8,6V18H10V14H12V18H14V6H8Z"/>
                                        </svg>
                                        <span class="text-lg font-semibold text-[var(--main-light-40)] leading-6 tracking-tight" id="referrals-label">
                                            {t8s!("Referrals")}
                                        </span>
                                    </div>
                                    <span class="text-lg font-semibold text-[var(--main-light)] leading-6 tracking-tight" id="referrals-value">
                                        {referrals}
                                    </span>
                                </div>
                                
                                <div class="flex items-center justify-between p-4 bg-[var(--other-light-5)] rounded-[14px] h-[52px]" id="commission-row">
                                    <div class="flex items-center gap-2" id="commission-container">
                                        <svg width="22" height="22" viewBox="0 0 24 24" fill="var(--main-light-40)" id="commission-icon">
                                            <path d="M18.5,4L19.66,8.35L18.7,8.61C18.25,7.74 17.79,6.87 17.26,6.43C16.73,6 16.11,6 15.5,6H13V16.5C13,17 13,17.5 13.33,17.75C13.67,18 14.33,18 15,18V19H9V18C9.67,18 10.33,18 10.67,17.75C11,17.5 11,17 11,16.5V6H8.5C7.89,6 7.27,6 6.74,6.43C6.21,6.87 5.75,7.74 5.3,8.61L4.34,8.35L5.5,4H18.5Z"/>
                                        </svg>
                                        <span class="text-lg font-semibold text-[var(--main-light-40)] leading-6 tracking-tight" id="commission-label">
                                            {t8s!("Commission")}
                                        </span>
                                    </div>
                                    <span class="text-lg font-semibold text-[var(--main-light)] leading-6 tracking-tight" id="commission-value">
                                        {format!("{:.0}%", percent)}
                                    </span>
                                </div>
                            </div>
                            
                            <div class="flex flex-col items-center gap-4 w-80" id="referral-program-container">
                                <h2 class="text-2xl font-semibold text-[var(--main-light)] text-center leading-[30px] tracking-tight" id="referral-program-title">
                                    {t8s!("Referral Program")}
                                </h2>
                                <p class="text-base text-[var(--main-light-40)] text-center leading-relaxed tracking-tight" id="referral-program-description">
                                    {t8s!("Invite friends and earn commission from their purchases. Share your referral links below.")}
                                </p>
                                
                                <div class="flex gap-2 w-80" id="buttons-container">
                                    <button 
                                        class="flex items-center justify-center p-3 gap-2 flex-1 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"
                                        on:click=handle_copy_website
                                        id="website-button"
                                    >
                                        <span id="website-button-text">
                                            {move || if copy_success_website.get() {
                                                t8s!("Copied!")
                                            } else {
                                                t8s!("Website")
                                            }}
                                        </span>
                                    </button>
                                    
                                    <button 
                                        class="flex items-center justify-center p-3 gap-2 flex-1 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"
                                        on:click=handle_copy_telegram
                                        id="telegram-button"
                                    >
                                        <span id="telegram-button-text">
                                            {move || if copy_success_telegram.get() {
                                                t8s!("Copied!")
                                            } else {
                                                t8s!("Telegram")
                                            }}
                                        </span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    }.into_any()
                } else {
                    view! {
                        <div class="flex flex-col items-center justify-center h-96 gap-4" id="no-data-container">
                            <span class="text-[var(--main-light-40)]">{t8s!("No referral data available")}</span>
                        </div>
                    }.into_any()
                }
            }}
        </Card>
    }
}

fn copy_to_clipboard(text: &str) {
    if let Some(window) = web_sys::window() {
        let navigator = window.navigator();
        let clipboard = navigator.clipboard();
        let _ = clipboard.write_text(text);
    }
}
