use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::components::prelude::*;
use crate::api::{get_banners, get_banner_image, Banner, AuthError};
use std::collections::HashMap;
use base64::Engine as _;

#[component]
pub fn PromotionsList(
    #[prop(optional)] id: Option<&'static str>,
    #[prop(optional)] class: Option<&'static str>,
) -> impl IntoView {
    let (banners, set_banners) = signal::<Option<Vec<Banner>>>(None);
    let (banner_images, set_banner_images) = signal::<HashMap<u32, String>>(HashMap::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal::<Option<String>>(None);

    Effect::new(move |_| {
        set_loading.set(true);
        set_error.set(None);
        
        spawn_local(async move {
            match get_banners().await {
                Ok(banner_list) => {
                    set_banners.set(Some(banner_list.clone()));
                    
                    let mut images = HashMap::new();
                    for banner in &banner_list {
                        match get_banner_image(banner.id).await {
                            Ok(image_bytes) => {
                                let base64_image = base64::engine::general_purpose::STANDARD.encode(&image_bytes);
                                let data_url = format!("data:image/jpeg;base64,{}", base64_image);
                                images.insert(banner.id, data_url);
                            }
                            Err(e) => {
                                log::warn!("Failed to fetch image for banner {}: {:?}", banner.id, e);
                            }
                        }
                    }
                    
                    set_banner_images.set(images);
                    set_error.set(None);
                }
                Err(e) => {
                    log::error!("Failed to fetch banners: {:?}", e);
                    set_error.set(Some(format!("{}: {}", t8s!("Failed to load promotions"), e)));
                    set_banners.set(None);
                }
            }
            set_loading.set(false);
        });
    });

    let base_classes = "flex flex-col gap-6 w-full";
    let final_classes = match class {
        Some(c) => format!("{} {}", base_classes, c),
        None => base_classes.to_string(),
    };

    view! {
        <section
            class=final_classes
            id=id.unwrap_or("promotions-list")
        >
            {move || {
                if loading.get() {
                    view! {
                        <div class="flex items-center justify-center w-full h-64" id="promotions-loading">
                            <div class="text-[rgba(255,249,247,0.6)] text-lg">
                                "Loading promotions..."
                            </div>
                        </div>
                    }.into_any()
                } else if let Some(error_msg) = error.get() {
                    view! {
                        <div class="flex items-center justify-center w-full h-64" id="promotions-error">
                            <div class="text-red-400 text-lg text-center">
                                {error_msg}
                            </div>
                        </div>
                    }.into_any()
                } else if let Some(banner_list) = banners.get() {
                    let images = banner_images.get();
                    
                    view! {
                        <div class="grid grid-cols-1 gap-6 w-full" id="promotions-grid">
                            {banner_list.into_iter().rev().enumerate().map(|(_index, banner)| {
                                let banner_id = banner.id;
                                let banner_name = banner.name.clone();
                                let banner_link = banner.link.clone();
                                let image_url = images.get(&banner_id).cloned();
                                
                                view! {
                                    <div 
                                        class="w-full max-w-[864px] h-[272px] bg-gradient-to-b from-[rgba(17,17,17,0.72)] to-[rgba(17,17,17,0.4)] rounded-3xl overflow-hidden hover:from-[rgba(17,17,17,0.8)] hover:to-[rgba(17,17,17,0.5)] transition-all duration-300 cursor-pointer m-auto"
                                        id=format!("promotion-block-{}", banner_id)
                                    >
                                        {if let Some(img_url) = image_url {
                                            view! {
                                                <a 
                                                    href=banner_link
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    class="block w-full h-full"
                                                    id=format!("promotion-link-{}", banner_id)
                                                >
                                                    <img 
                                                        src=img_url
                                                        alt=banner_name.clone()
                                                        class="w-full h-full object-cover rounded-3xl"
                                                        id=format!("promotion-image-{}", banner_id)
                                                    />
                                                </a>
                                            }.into_any()
                                        } else {
                                            view! {
                                                <a 
                                                    href=banner_link
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    class="block w-full h-full flex items-center justify-center"
                                                    id=format!("promotion-link-{}", banner_id)
                                                >
                                                    <div class="text-center">
                                                        <div class="text-xl font-semibold text-[rgba(255,249,247,0.8)] mb-2">
                                                            {banner_name.clone()}
                                                        </div>
                                                        <div class="text-sm text-[rgba(255,249,247,0.6)]">
                                                            "Special Offer"
                                                        </div>
                                                    </div>
                                                </a>
                                            }.into_any()
                                        }}
                                    </div>
                                }
                            }).collect::<Vec<_>>()}
                        </div>
                    }.into_any()
                } else {
                    view! {
                        <div class="flex items-center justify-center w-full h-64" id="promotions-empty">
                            <div class="text-[rgba(255,249,247,0.6)] text-lg">
                                "No promotions available at the moment"
                            </div>
                        </div>
                    }.into_any()
                }
            }}
        </section>
    }
}
