// Main Kanban board component

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

use crate::api::{ApiClient, Task, TaskStatus};
use crate::components::KanbanColumn;
use crate::config::AppConfig;

/// Main Kanban board component
#[component]
pub fn KanbanBoard(project_id: String) -> impl IntoView {
    let api_client = ApiClient::new(&AppConfig::load());

    let (tasks, set_tasks) = signal(Vec::<Task>::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal(None::<String>);

    // Fetch tasks on mount
    Effect::new(move |_| {
        let api = api_client.clone();
        let pid = project_id.clone();
        spawn_local(async move {
            match api.fetch_tasks(&pid).await {
                Ok(t) => {
                    set_tasks.set(t);
                    set_loading.set(false);
                }
                Err(e) => {
                    warn!("Failed to fetch tasks: {}", e);
                    set_error.set(Some(e));
                    set_loading.set(false);
                }
            }
        });
    });

    // Memoized filtered tasks by status
    let todo_tasks = Memo::new(move |_| {
        tasks
            .get()
            .into_iter()
            .filter(|t| matches!(t.status, TaskStatus::Todo))
            .collect::<Vec<_>>()
    });

    let doing_tasks = Memo::new(move |_| {
        tasks
            .get()
            .into_iter()
            .filter(|t| matches!(t.status, TaskStatus::Doing))
            .collect::<Vec<_>>()
    });

    let review_tasks = Memo::new(move |_| {
        tasks
            .get()
            .into_iter()
            .filter(|t| matches!(t.status, TaskStatus::Review))
            .collect::<Vec<_>>()
    });

    let done_tasks = Memo::new(move |_| {
        tasks
            .get()
            .into_iter()
            .filter(|t| matches!(t.status, TaskStatus::Done))
            .collect::<Vec<_>>()
    });

    view! {
        <div class="w-full h-full p-6 overflow-x-auto">
            <Show
                when=move || !loading.get()
                fallback=|| view! {
                    <div class="flex items-center justify-center h-full">
                        <div class="text-center text-white">
                            <div class="text-xl font-semibold mb-2">"Loading tasks..."</div>
                            <div class="text-sm text-gray-400">"Fetching from backend"</div>
                        </div>
                    </div>
                }
            >
                {move || {
                    if let Some(err) = error.get() {
                        view! {
                            <div class="flex items-center justify-center h-full">
                                <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 tasks"</div>
                                    <div class="text-sm text-red-300">{err}</div>
                                </div>
                            </div>
                        }.into_any()
                    } else {
                        view! {
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 min-w-max">
                                <KanbanColumn
                                    title="To Do"
                                    color="from-rose-500/90 to-rose-600/90"
                                    tasks=todo_tasks.into()
                                />
                                <KanbanColumn
                                    title="Doing"
                                    color="from-orange-500/90 to-orange-600/90"
                                    tasks=doing_tasks.into()
                                />
                                <KanbanColumn
                                    title="Review"
                                    color="from-blue-500/90 to-blue-600/90"
                                    tasks=review_tasks.into()
                                />
                                <KanbanColumn
                                    title="Done"
                                    color="from-green-500/90 to-green-600/90"
                                    tasks=done_tasks.into()
                                />
                            </div>
                        }.into_any()
                    }
                }}
            </Show>
        </div>
    }
}
