// Agents marketplace page

use leptos::prelude::*;
use leptos::task::spawn_local;
use log::warn;

use crate::api::{Agent, ApiClient};
use crate::components::{Badge, Button, Card, GlowColor, NavBar};
use crate::config::AppConfig;

/// Agents marketplace page
#[component]
pub fn AgentsPage() -> impl IntoView {
    let api_client = ApiClient::new(&AppConfig::load());
    let (agents, set_agents) = signal(Vec::<Agent>::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal(None::<String>);

    // Fetch agents on mount
    Effect::new(move |_| {
        let api = api_client.clone();
        spawn_local(async move {
            match api.fetch_agents().await {
                Ok(a) => {
                    set_agents.set(a);
                    set_loading.set(false);
                }
                Err(e) => {
                    warn!("Failed to fetch agents: {}", e);
                    set_error.set(Some(e));
                    set_loading.set(false);
                }
            }
        });
    });

    view! {
        <div class="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
            <NavBar />

            <div class="container mx-auto px-6 py-8">
                <h1 class="text-3xl font-bold text-white mb-8">"Agent Marketplace"</h1>

                <Show
                    when=move || !loading.get()
                    fallback=|| view! {
                        <div class="text-center py-12">
                            <div class="text-xl text-white">"Loading agents..."</div>
                        </div>
                    }
                >
                    {move || {
                        if let Some(err) = error.get() {
                            view! {
                                <div class="bg-red-500/20 border border-red-500/50 rounded-lg p-6 text-center">
                                    <div class="text-red-400 font-semibold mb-2">"Error loading agents"</div>
                                    <div class="text-sm text-red-300">{err}</div>
                                </div>
                            }.into_any()
                        } else if agents.get().is_empty() {
                            view! {
                                <div class="text-center py-12">
                                    <div class="text-xl text-gray-400">"No agents available"</div>
                                </div>
                            }.into_any()
                        } else {
                            view! {
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                    <For
                                        each=move || agents.get()
                                        key=|agent| agent.id.clone()
                                        children=move |agent| {
                                            let name = agent.name.clone();
                                            let role = format!("{:?}", agent.role);
                                            let llm_info = format!("LLM: {} {}", agent.llm_provider, agent.llm_model);
                                            let capabilities = agent.capabilities.clone();
                                            view! {
                                                <Card glow=GlowColor::Cyan hover_effect=true>
                                                    <div class="flex items-start justify-between mb-3">
                                                        <h3 class="text-lg font-semibold text-white">
                                                            {name}
                                                        </h3>
                                                        <Badge class="bg-cyan-500/20 text-cyan-400 text-xs">
                                                            {role}
                                                        </Badge>
                                                    </div>
                                                    <p class="text-gray-400 text-sm mb-4">
                                                        {llm_info}
                                                    </p>
                                                    <div class="flex gap-2 flex-wrap mb-4">
                                                        {capabilities.iter().take(3).map(|cap| {
                                                            let capability = cap.clone();
                                                            view! {
                                                                <Badge class="bg-green-500/20 text-green-400 text-xs">
                                                                    {capability}
                                                                </Badge>
                                                            }
                                                        }).collect_view()}
                                                    </div>
                                                    <Button class="w-full">
                                                        "View Agent"
                                                    </Button>
                                                </Card>
                                            }
                                        }
                                    />
                                </div>
                            }.into_any()
                        }
                    }}
                </Show>
            </div>
        </div>
    }
}
