// Agents marketplace page

use leptos::prelude::*;
use leptos::task::spawn_local;
use log::warn;
use vapora_leptos_ui::{Pagination, Spinner, Table, TableColumn};

use crate::api::{Agent, ApiClient};
use crate::components::NavBar;
use crate::config::AppConfig;

const ITEMS_PER_PAGE: usize = 10;

/// 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>);
    let (current_page, set_current_page) = signal(1usize);

    // 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="flex flex-col items-center justify-center py-12 gap-4">
                            <Spinner />
                            <div class="text-lg text-white/80">"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 {
                            // Convert agents to table format
                            let columns = vec![
                                TableColumn::new("Name", "name").sortable(),
                                TableColumn::new("Role", "role").sortable(),
                                TableColumn::new("LLM Provider", "provider").sortable(),
                                TableColumn::new("Model", "model"),
                                TableColumn::new("Status", "status").sortable(),
                                TableColumn::new("Capabilities", "capabilities"),
                            ];

                            let all_agents = agents.get();
                            let total_items = all_agents.len();
                            let total_pages = total_items.div_ceil(ITEMS_PER_PAGE);

                            // Paginate agents
                            let page = current_page.get();
                            let start_idx = (page - 1) * ITEMS_PER_PAGE;
                            let end_idx = (start_idx + ITEMS_PER_PAGE).min(total_items);

                            let rows: Vec<Vec<String>> = all_agents
                                .into_iter()
                                .skip(start_idx)
                                .take(end_idx - start_idx)
                                .map(|agent| {
                                    let capabilities_str = agent.capabilities
                                        .iter()
                                        .take(3)
                                        .cloned()
                                        .collect::<Vec<_>>()
                                        .join(", ");

                                    vec![
                                        agent.name,
                                        format!("{:?}", agent.role),
                                        agent.llm_provider,
                                        agent.llm_model,
                                        format!("{:?}", agent.status),
                                        capabilities_str,
                                    ]
                                })
                                .collect();

                            view! {
                                <div class="flex flex-col gap-6">
                                    <Table columns=columns rows=rows />

                                    {move || {
                                        if total_pages > 1 {
                                            view! {
                                                <div class="flex justify-center">
                                                    <Pagination
                                                        current_page=current_page.get()
                                                        total_pages=total_pages
                                                        on_page_change=Callback::new(move |page| {
                                                            set_current_page.set(page);
                                                        })
                                                    />
                                                </div>
                                            }.into_any()
                                        } else {
                                            view! { <div /> }.into_any()
                                        }
                                    }}
                                </div>
                            }.into_any()
                        }
                    }}
                </Show>
            </div>
        </div>
    }
}
