// Projects list page

use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::components::A;
use log::warn;

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

/// Projects list page
#[component]
pub fn ProjectsPage() -> impl IntoView {
    let api_client = ApiClient::new(&AppConfig::load());
    let (projects, set_projects) = signal(Vec::<Project>::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal(None::<String>);

    // Fetch projects on mount
    Effect::new(move |_| {
        let api = api_client.clone();
        spawn_local(async move {
            match api.fetch_projects("default").await {
                Ok(p) => {
                    set_projects.set(p);
                    set_loading.set(false);
                }
                Err(e) => {
                    warn!("Failed to fetch projects: {}", 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">
                <div class="flex items-center justify-between mb-8">
                    <h1 class="text-3xl font-bold text-white">"Projects"</h1>
                    <Button>
                        "+ New Project"
                    </Button>
                </div>

                <Show
                    when=move || !loading.get()
                    fallback=|| view! {
                        <div class="text-center py-12">
                            <div class="text-xl text-white">"Loading projects..."</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 projects"</div>
                                    <div class="text-sm text-red-300">{err}</div>
                                </div>
                            }.into_any()
                        } else if projects.get().is_empty() {
                            view! {
                                <div class="text-center py-12">
                                    <div class="text-xl text-gray-400 mb-4">"No projects yet"</div>
                                    <Button>
                                        "Create Your First Project"
                                    </Button>
                                </div>
                            }.into_any()
                        } else {
                            view! {
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                    <For
                                        each=move || projects.get()
                                        key=|project| project.id.clone().unwrap_or_default()
                                        children=move |project| {
                                            let project_id = project.id.clone().unwrap_or_default();
                                            let title = project.title.clone();
                                            let description = project.description.clone().unwrap_or_default();
                                            let features = project.features.clone();
                                            view! {
                                                <A href=format!("/projects/{}", project_id)>
                                                    <Card hover_effect=true>
                                                        <h3 class="text-lg font-semibold text-white mb-2">
                                                            {title}
                                                        </h3>
                                                        <p class="text-gray-400 text-sm mb-4">
                                                            {description}
                                                        </p>
                                                        <div class="flex gap-2 flex-wrap">
                                                            {features.iter().map(|f| {
                                                                let feat = f.clone();
                                                                view! {
                                                                    <Badge class="bg-blue-500/20 text-blue-400">
                                                                        {feat}
                                                                    </Badge>
                                                                }
                                                            }).collect_view()}
                                                        </div>
                                                    </Card>
                                                </A>
                                            }
                                        }
                                    />
                                </div>
                            }.into_any()
                        }
                    }}
                </Show>
            </div>
        </div>
    }
}
