use leptos::prelude::*;
use std::ops::Div;
use crate::components::card::{Card, CardVariant};
use crate::components::layout::PageContent;
use crate::components::accent_hero::AccentHero;
use crate::components::proxy_list::ProxyItems;
use crate::page::prelude::*;
use leptos::task::spawn_local;
use crate::api::{get_prices, calculate_discounts, PoolPrices, AuthError, get_proxy_countries};
use rust_shared::repository::model::{PoolType, Country};
use web_sys::wasm_bindgen::JsCast;

#[derive(Clone, Debug)]
pub struct Tariff {
    pub amount: u32,
    pub unit: String,
    pub discount: f64,
    pub original_price: f64,
    pub final_price: f64,
    pub price_per_gb: f64,
}

impl Tariff {
    pub fn new(amount: u32, unit: String, discount: f64, original_price: f64, final_price: f64, price_per_gb: f64) -> Self {
        Self {
            amount,
            unit,
            discount,
            original_price,
            final_price,
            price_per_gb,
        }
    }
}

#[component]
pub fn PricesPage() -> impl IntoView {
    let scroll_progress = RwSignal::new(0.0);
    let slider_ref = NodeRef::<leptos::html::Div>::new();
    let progress_bar_ref = NodeRef::<leptos::html::Div>::new();
    let is_dragging = RwSignal::new(false);
    
    // State for pricing data
    let prices = RwSignal::<Option<PoolPrices>>::new(None);
    let tariffs = RwSignal::<Vec<Tariff>>::new(Vec::new());
    let selected_pool = RwSignal::new("residential".to_string());
    let loading = RwSignal::new(true);
    let error = RwSignal::<Option<String>>::new(None);
    
    // State for proxy data
    let proxy_loading = RwSignal::new(false);
    let proxy_error = RwSignal::<Option<String>>::new(None);
    let proxy_data = RwSignal::<Option<Vec<Country>>>::new(None);

    let prices_url = t8s!("/en/prices");

    create_effect(move |_| {
        if let Some(window) = web_sys::window() {
            if let Ok(path) = window.location().pathname() {
                log::debug!("PricesPage: path: '{}'", path);
                if path == prices_url {
                    log::debug!("PricesPage: path is prices_url, scrolling to prices");
                    if let Some(el) = window.document().and_then(|d| d.get_element_by_id("prices")) {
                        log::debug!("PricesPage: element found, scrolling to prices");
                        el.scroll_into_view_with_bool(true);
                    }
                }
            }
        }
    });
   
    // Function to calculate tariffs from prices
    let calculate_tariffs_from_prices = {
        let tariffs = tariffs.clone();
        let error = error.clone();
        let selected_pool = selected_pool.clone();
        
        move |prices_data: PoolPrices| {
            let tariffs = tariffs.clone();
            let error = error.clone();
            let selected_pool = selected_pool.clone();
            
            spawn_local(async move {
                let amounts = vec![100, 300, 500, 1000];
                match calculate_discounts(amounts.clone()).await {
                    Ok(discounts) => {
                        let base_price = match selected_pool.get().as_str() {
                            "residential" => prices_data.residential,
                            "residential_premium" => prices_data.residential_premium,
                            "datacenter" => prices_data.datacenter,
                            "mobile" => prices_data.mobile,
                            _ => prices_data.residential,
                        };
                        
                        let mut calculated_tariffs = Vec::new();
                        
                        // Add 1GB tariff (no discount)
                        calculated_tariffs.push(Tariff::new(
                            1,
                            "GB".to_string(),
                            0.0,
                            base_price,
                            base_price,
                            base_price,
                        ));
                        
                        // Add calculated tariffs
                        for (amount, discount) in amounts.iter().zip(discounts.iter()) {
                            let original_price = *amount as f64 * base_price;
                            let final_price = original_price * (1.0 - discount);
                            let price_per_gb = final_price / (*amount as f64);
                            
                            calculated_tariffs.push(Tariff::new(
                                *amount,
                                "GB".to_string(),
                                *discount,
                                original_price,
                                final_price,
                                price_per_gb,
                            ));
                        }
                        
                        
                        tariffs.set(calculated_tariffs);
                    }
                    Err(e) => {
                        error.set(Some(format!("Failed to calculate discounts: {}", e)));
                    }
                }
            });
        }
    };
    
    // Initial data fetch
    Effect::new(move |_| {
        let prices = prices.clone();
        let loading = loading.clone();
        let error = error.clone();
        let calculate_tariffs_from_prices = calculate_tariffs_from_prices.clone();
        
        spawn_local(async move {
            loading.set(true);
            error.set(None);
            
            match get_prices().await {
                Ok(prices_data) => {
                    prices.set(Some(prices_data.clone()));
                    calculate_tariffs_from_prices(prices_data);
                }
                Err(e) => {
                    error.set(Some(format!("Failed to fetch prices: {}", e)));
                }
            }
            
            loading.set(false);
        });
    });
    
    // Effect to recalculate tariffs when pool changes
    Effect::new(move |_| {
        let _pool = selected_pool.get();
        if let Some(prices_data) = prices.get() {
            calculate_tariffs_from_prices(prices_data);
        }
    });
    
    // Effect to load proxy data
    Effect::new(move |_| {
        let proxy_loading = proxy_loading.clone();
        let proxy_error = proxy_error.clone();
        let proxy_data = proxy_data.clone();
        
        spawn_local(async move {
            proxy_loading.set(true);
            proxy_error.set(None);
            
            match get_proxy_countries(PoolType::Datacenter).await {
                Ok(countries) => {
                    proxy_data.set(Some(countries));
                    proxy_error.set(None);
                }
                Err(e) => {
                    log::error!("Failed to fetch proxy countries: {:?}", e);
                    proxy_error.set(Some(format!("Failed to load proxy data: {}", e)));
                    proxy_data.set(None);
                }
            }
            
            proxy_loading.set(false);
        });
    });
    
    view! {
        <script src="scripts/custom-slider.js"/>

        <div id="pricing-hero">
            <AccentHero/>
        </div>
        
        <PageContent>

            <div class="custom-slider w-full">
              <div class="flex flex-row gap-[16px] mt-[96px] w-full custom-slider__track scrollbar-hide" id="proxy-types">
                  <Card padding="p-[24px]" id="residential-proxy-card">
                      <h3> {t8s!("Residential")} </h3>
                      <ul>
                          <li>{t8s!("Over 15 million unique IPs in 195 countries")}</li>
                          <li>{t8s!("Free country selection")}</li>
                          <li>{t8s!("Targeting by state/city/ZIP/ASN")}</li>
                          <li>{t8s!("Pay per traffic without expiration")}</li>
                          <li>{t8s!("Rotating and sticky sessions")}</li>
                          <li>{t8s!("10,000 threads")}</li>
                      </ul>
                  </Card>
                  <Card padding="p-[24px]" id="premium-residential-proxy-card">
                      <h3 class="flex flex-row h-fit gap-[8px]">
                          <span> {t8s!("Residential")} </span>
                          <div class="premium-label my-auto">"PREM"</div>
                      </h3>
                      <ul>
                          <li>{t8s!("Over 15 million unique IPs in 195 countries")}</li>
                          <li>{t8s!("Free country selection")}</li>
                          <li>{t8s!("Targeting by state/city/ZIP/ASN")}</li>
                          <li>{t8s!("Pay per traffic without expiration")}</li>
                          <li>{t8s!("Rotating and sticky sessions")}</li>
                          <li>{t8s!("10,000 threads")}</li>
                      </ul>
                  </Card>
                  <Card padding="p-[24px]" id="datacenter-proxy-card">
                      <h3> {t8s!("Datacenter")} </h3>
                      <ul>
                          <li>{t8s!("Over 15 million unique IPs in 195 countries")}</li>
                          <li>{t8s!("Free country selection")}</li>
                          <li>{t8s!("Targeting by state/city/ZIP/ASN")}</li>
                          <li>{t8s!("Pay per traffic without expiration")}</li>
                          <li>{t8s!("Rotating and sticky sessions")}</li>
                          <li>{t8s!("10,000 threads")}</li>
                      </ul>
                  </Card>
                  <Card padding="p-[24px]" id="mobile-proxy-card">
                      <h3> {t8s!("Mobile")} </h3>
                      <ul>
                          <li>{t8s!("Over 15 million unique IPs in 195 countries")}</li>
                          <li>{t8s!("Free country selection")}</li>
                          <li>{t8s!("Targeting by state/city/ZIP/ASN")}</li>
                          <li>{t8s!("Pay per traffic without expiration")}</li>
                          <li>{t8s!("Rotating and sticky sessions")}</li>
                          <li>{t8s!("10,000 threads")}</li>
                      </ul>
                  </Card>
              </div>
            </div>

            <div id="prices" class="mt-[100px]">
                <div id="pricing-card" class="flex flex-col items-start p-8 gap-12 w-full bg-gradient-to-b from-[rgba(17,17,17,0.72)] to-[rgba(17,17,17,0.4)] rounded-3xl">
                    <div class="flex flex-col items-start p-0 gap-4 w-full">
                        <h2 class="font-semibold text-4xl leading-[42px] tracking-[-0.02em] text-[rgba(255,249,247,0.95)]">
                            {t8s!("Pricing")}
                        </h2>
                        <p class="font-normal text-base leading-[22px] tracking-[-0.02em] text-[rgba(255,249,247,0.4)]">
                            {t8s!("No limits! We don't restrict the minimum amount of traffic you can buy, purchase as much as you need!")}
                        </p>
                    </div>

                    <div class="flex flex-col items-start p-0 gap-8 w-full">
                        <div id="prices-selector" class="flex flex-row items-start p-0 gap-2 w-full">
                            <button 
                                class=move || format!("flex flex-row justify-center items-center p-[14px] gap-2 h-[52px] rounded-[14px] flex-1 transition-all duration-300 {}", 
                                    if selected_pool.get() == "residential" { 
                                        "bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0px_0px_100px_rgba(255,68,0,0.5),0px_0px_200px_#FF4400]" 
                                    } else { 
                                        "border border-[rgba(255,249,247,0.4)] hover:border-[rgba(255,249,247,0.6)]" 
                                    }
                                )
                                on:click=move |_| selected_pool.set("residential".to_string())
                            >
                                <span class=move || format!("w-full h-6 font-semibold text-lg leading-6 tracking-[-0.02em] {}", 
                                    if selected_pool.get() == "residential" { 
                                        "text-[rgba(255,249,247,0.8)]" 
                                    } else { 
                                        "text-[rgba(255,249,247,0.4)]" 
                                    }
                                )>
                                    {t8r!("Residential")}
                                </span>
                            </button>
                            
                            <button 
                                class=move || format!("flex flex-row justify-center items-center p-[14px] gap-2 h-[52px] rounded-[14px] flex-1 transition-all duration-300 {}", 
                                    if selected_pool.get() == "residential_premium" { 
                                        "bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0px_0px_100px_rgba(255,68,0,0.5),0px_0px_200px_#FF4400]" 
                                    } else { 
                                        "border border-[rgba(255,249,247,0.4)] hover:border-[rgba(255,249,247,0.6)]" 
                                    }
                                )
                                on:click=move |_| selected_pool.set("residential_premium".to_string())
                            >
                                <span class=move || format!("w-full h-6 font-semibold text-lg leading-6 tracking-[-0.02em] {}", 
                                    if selected_pool.get() == "residential_premium" { 
                                        "text-[rgba(255,249,247,0.8)]" 
                                    } else { 
                                        "text-[rgba(255,249,247,0.4)]" 
                                    }
                                )>
                                    {t8r!("Residential")}
                                </span>
                                <div class="flex flex-row justify-center items-center px-[6px] py-[1px] gap-[10px] w-[47px] h-[22px] bg-[rgba(255,249,247,0.2)] rounded-[6px]">
                                    <span class="w-full h-[18px] font-bold text-xs leading-[18px] tracking-[-0.02em] uppercase text-[rgba(255,249,247,0.6)]">
                                        "PREM"
                                    </span>
                                </div>
                            </button>
                            
                            <button 
                                class=move || format!("flex flex-row justify-center items-center p-[14px] gap-2 h-[52px] rounded-[14px] flex-1 transition-all duration-300 {}", 
                                    if selected_pool.get() == "datacenter" { 
                                        "bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0px_0px_100px_rgba(255,68,0,0.5),0px_0px_200px_#FF4400]" 
                                    } else { 
                                        "border border-[rgba(255,249,247,0.4)] hover:border-[rgba(255,249,247,0.6)]" 
                                    }
                                )
                                on:click=move |_| selected_pool.set("datacenter".to_string())
                            >
                                <span class=move || format!("w-full h-6 font-semibold text-lg leading-6 tracking-[-0.02em] {}", 
                                    if selected_pool.get() == "datacenter" { 
                                        "text-[rgba(255,249,247,0.8)]" 
                                    } else { 
                                        "text-[rgba(255,249,247,0.4)]" 
                                    }
                                )>
                                    {t8r!("Datacenter")}
                                </span>
                            </button>
                            
                            <button 
                                class=move || format!("flex flex-row justify-center items-center p-[14px] gap-2 h-[52px] rounded-[14px] flex-1 transition-all duration-300 {}", 
                                    if selected_pool.get() == "mobile" { 
                                        "bg-gradient-to-b from-[#FF5011] to-[#FF4400] shadow-[0px_0px_100px_rgba(255,68,0,0.5),0px_0px_200px_#FF4400]" 
                                    } else { 
                                        "border border-[rgba(255,249,247,0.4)] hover:border-[rgba(255,249,247,0.6)]" 
                                    }
                                )
                                on:click=move |_| selected_pool.set("mobile".to_string())
                            >
                                <span class=move || format!("w-full h-6 font-semibold text-lg leading-6 tracking-[-0.02em] {}", 
                                    if selected_pool.get() == "mobile" { 
                                        "text-[rgba(255,249,247,0.8)]" 
                                    } else { 
                                        "text-[rgba(255,249,247,0.4)]" 
                                    }
                                )>
                                    {t8r!("Mobile")}
                                </span>
                            </button>
                        </div>
                    <div class="custom-slider w-full">
                        <div
                            class="custom-slider__track flex flex-row items-start p-0 gap-2 w-full h-[238px] overflow-x-scroll scrollbar-hide"
                            id="prices-slider"
                            node_ref=slider_ref
                        >
                            {move || {
                                if loading.get() {
                                    view! {
                                        <div class="flex items-center justify-center w-full h-full">
                                            <span class="text-[rgba(255,249,247,0.4)]">{t8r!("Loading...")}</span>
                                        </div>
                                    }.into_any()
                                } else if let Some(error_msg) = error.get() {
                                    view! {
                                        <div class="flex items-center justify-center w-full h-full">
                                            <span class="text-red-400">{error_msg}</span>
                                        </div>
                                    }.into_any()
                                } else {
                                    let tariffs_list = tariffs.get();
                                    view! {
                                        <>
                                            {tariffs_list.iter().enumerate().map(|(index, tariff)| {
                                                let show_original = tariff.discount > 0.0;
                                                view! {
                                                    <PricesCard 
                                                        id=format!("price-card-{}", index)
                                                        amount=tariff.amount.to_string()
                                                        unit=tariff.unit.clone()
                                                        current_price=format!("${:.2}", tariff.final_price)
                                                        original_price=if show_original { format!("${:.2}", tariff.original_price) } else { "$0.00".to_string() }
                                                        price_per_gb=format!("${:.2}", tariff.price_per_gb)
                                                    />
                                                }.into_any()
                                            }).collect::<Vec<_>>()}
                                        </>
                                    }.into_any()
                                }
                            }}
                        </div>

                        <div class="flex flex-col justify-center items-center p-0 gap-[10px] w-full h-2 mt-[10px]">
                            <div
                                class="w-[238px] h-2 bg-[rgba(255,249,247,0.05)] rounded-full progress-bar"
                                node_ref=progress_bar_ref
                            >
                                    <div 
                                        class="h-2 bg-[rgba(255,249,247,0.6)] rounded-full transition-all duration-300"
                                        style=move || format!("width: {}%", scroll_progress.get())
                                    ></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div id="full-control-block">
                <div>
                    {t8r!("Full control on your side")}
                </div>
                <div>
                    {t8r!("Providing reliable, secure, and high-performance infrastructure for Internet access")}
                </div>
            </div>

            <Card variant=CardVariant::L1 max_width="w-full" id="telegram-bot-card">
                <div class="flex flex-row gap-[16px]">
                    <div class="flex flex-col justify-between">
                        <h2 class="text-[36px] font-semibold leading-[42px] text-[var(--main-light)]">
                            {t8s!("Smart Telegram Bot")}
                        </h2>
                        <p class="text-[16px] leading-[22px] text-[var(--text-muted)] mt-[16px]">
                            {t8s!("Use all the functionality of our project directly through the Telegram Bot")}
                        </p>
                        <a class="button mt-auto flex flex-row" href="https://t.me/v_proxy_bot" target="_blank">
                            <span class="text-[var(--main-dark-text)] text-[18px] font-semibold">
                                {t8s!("Go to Bot")}
                            </span>
                            <img src="/arrow-icon.svg" class="ml-auto">
                            </img>
                        </a>
                    </div>
                    <img class="rounded-2xl" src=t8s!("/tg-bot.en.png")>
                    </img>
                </div>
            </Card>

            <div id="pros-block">
                <div>
                </div>
            </div>

            <Card variant=CardVariant::L1 max_width="w-full" class="mt-[96px]" id="ip-pool-card">
                <div class="flex flex-row gap-[16px]">
                    <div class="flex flex-col p-[16px]">
                        <h2 class="text-[36px] font-semibold leading-[42px] text-[var(--main-light)]">
                            {t8s!("IP Pool by Countries")}
                        </h2>
                        <p class="text-[16px] leading-[22px] text-[var(--text-muted)] mt-[16px]">
                            {t8s!("You can see the number of online proxies for each country in real-time")}
                        </p>
                        <a class="button mt-auto flex flex-row" href=t8r!("/en/proxy")>
                            <span class="text-[var(--main-dark-text)] text-[18px] font-semibold">
                                {t8s!("Proxy Online")}
                            </span>
                            <img src="/arrow-icon.svg" class="ml-auto">
                            </img>
                        </a>
                    </div>
                    <ProxyItems 
                        loading=proxy_loading.read_only()
                        error=proxy_error.read_only()
                        proxy_data=proxy_data.read_only()
                    />
                </div>
            </Card>
        </PageContent>
    }
}

#[component]
pub fn PricesCard(
    #[prop(optional)] id: Option<String>,
    amount: String,
    unit: String,
    current_price: String,
    original_price: String,
    price_per_gb: String,
) -> impl IntoView {
    let show_original = original_price != "$0.00";
    let is_tb = unit == "TB";
    
    view!{
        <div id=id class="box-border flex flex-col justify-between items-center p-6 gap-[10px] w-[238px] h-[238px] bg-gradient-to-b from-[rgba(255,249,247,0.09)] to-[rgba(255,249,247,0.005)] bg-[rgba(17,17,17,0.4)] rounded-[14px] flex-none">
            <div class="flex flex-row justify-center items-start p-0 gap-1 mx-auto w-[190px] h-[30px]">
                <span class="w-auto h-[30px] font-semibold text-2xl leading-[30px] tracking-[-0.02em] text-[rgba(255,249,247,0.4)]">
                    {current_price}
                </span>
                {show_original.then(|| view! {
                    <s class="w-auto h-6 font-semibold text-lg leading-6 tracking-[-0.02em] line-through text-[rgba(255,249,247,0.2)]">
                        {original_price}
                    </s>
                })}
            </div>
            
            <div class="flex flex-row justify-center items-end p-0 gap-2 mx-auto w-[190px] h-[54px]">
                <span class="w-auto h-[54px] font-semibold text-5xl leading-[54px] tracking-[-0.02em] text-[rgba(255,249,247,0.95)]">
                    {amount}
                </span>
                <span class=format!("w-auto h-[42px] font-semibold text-4xl leading-[42px] tracking-[-0.02em] text-[rgba(255,249,247,0.4)] {}", if is_tb { "block" } else { "block" })>
                    {unit}
                </span>
            </div>
            
            <div class="flex flex-row justify-center items-center p-0 gap-1 mx-auto w-[190px] h-[22px]">
                <span class="w-auto h-[22px] font-normal text-base leading-[22px] tracking-[-0.02em] text-[rgba(255,249,247,0.2)]">
                    {t8s!("Price per 1 GB -")}
                </span>
                <span class="w-auto h-[22px] font-normal text-base leading-[22px] tracking-[-0.02em] text-[rgba(255,249,247,0.2)]">
                    {price_per_gb}
                </span>
            </div>
        </div>
    }
}

