// Projects list page

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

/// Extract value from input event
#[cfg(target_arch = "wasm32")]
fn event_target_value(ev: &leptos::ev::Event) -> String {
    use wasm_bindgen::JsCast;
    ev.target()
        .and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
        .map(|input| input.value())
        .unwrap_or_default()
}

#[cfg(not(target_arch = "wasm32"))]
fn event_target_value(_ev: &leptos::ev::Event) -> String {
    String::new()
}

use vapora_leptos_ui::{
    use_toast, FormField, Input, Modal, Pagination, Spinner, StatCard, ToastType,
};

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

const ITEMS_PER_PAGE: usize = 9; // 3x3 grid

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

    // Modal state
    let (show_create_modal, set_show_create_modal) = signal(false);
    let (project_title, set_project_title) = signal(String::new());
    let (_project_description, set_project_description) = signal(String::new());
    let (form_error, set_form_error) = signal::<Option<String>>(None);

    // Fetch projects on mount
    Effect::new(move |_| {
        let api = api_client.clone();
        spawn_local(async move {
            match api.fetch_projects("default").await {
                Ok(p) => {
                    let count = p.len();
                    set_projects.set(p);
                    set_loading.set(false);
                    toast.show_toast(format!("Loaded {} projects", count), ToastType::Success);
                }
                Err(e) => {
                    warn!("Failed to fetch projects: {}", e);
                    set_error.set(Some(e.clone()));
                    set_loading.set(false);
                    toast.show_toast(format!("Failed to load projects: {}", e), ToastType::Error);
                }
            }
        });
    });

    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 on_click=Callback::new(move |_| set_show_create_modal.set(true))>
                        "+ New Project"
                    </Button>
                </div>

                <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 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 {
                            // Compute project metrics
                            let all_projects = projects.get();
                            let total_projects = all_projects.len();
                            let total_pages = total_projects.div_ceil(ITEMS_PER_PAGE);

                            // Paginate projects
                            let page = current_page.get();
                            let start_idx = (page - 1) * ITEMS_PER_PAGE;
                            let end_idx = (start_idx + ITEMS_PER_PAGE).min(total_projects);
                            let paginated_projects: Vec<Project> = all_projects
                                .into_iter()
                                .skip(start_idx)
                                .take(end_idx - start_idx)
                                .collect();

                            view! {
                                // Stats cards
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                                    <StatCard
                                        label="Total Projects".to_string()
                                        value=total_projects.to_string()
                                    />
                                    <StatCard
                                        label="Active".to_string()
                                        value=total_projects.to_string()
                                        trend_positive=true
                                    />
                                    <StatCard
                                        label="Completed".to_string()
                                        value="0".to_string()
                                    />
                                </div>

                                // Projects grid
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
                                    <For
                                        each=move || paginated_projects.clone()
                                        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 hoverable=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>

                                // Pagination
                                {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()
                                    }
                                }}
                            }.into_any()
                        }
                    }}
                </Show>
            </div>

            // Create Project Modal
            <Show when=move || show_create_modal.get()>
                <Modal on_close=Callback::new(move |_| {
                    set_show_create_modal.set(false);
                    set_project_title.set(String::new());
                    set_project_description.set(String::new());
                    set_form_error.set(None);
                })>
                    <h2 class="text-2xl font-bold text-white mb-6">"Create New Project"</h2>

                    <form on:submit=move |ev| {
                        ev.prevent_default();

                        // Simple validation
                        if project_title.get().trim().is_empty() {
                            set_form_error.set(Some("Project title is required".to_string()));
                            return;
                        }

                        // Show success toast and close modal
                        toast.show_toast(
                            "Project created successfully!".to_string(),
                            ToastType::Success
                        );
                        set_show_create_modal.set(false);
                        set_project_title.set(String::new());
                        set_project_description.set(String::new());
                    }>
                        <div class="flex flex-col gap-4">
                            {move || {
                                let has_error = form_error.get().is_some();
                                if let Some(err_msg) = form_error.get() {
                                    view! {
                                        <FormField
                                            label="Project Title".to_string()
                                            error=err_msg
                                            required=true
                                            has_error=has_error
                                        >
                                            <Input
                                                on_input=Callback::new(move |ev| {
                                                    let value = event_target_value(&ev);
                                                    set_project_title.set(value);
                                                    set_form_error.set(None);
                                                })
                                                placeholder="Enter project title"
                                            />
                                        </FormField>
                                    }.into_any()
                                } else {
                                    view! {
                                        <FormField
                                            label="Project Title".to_string()
                                            required=true
                                            has_error=false
                                        >
                                            <Input
                                                on_input=Callback::new(move |ev| {
                                                    let value = event_target_value(&ev);
                                                    set_project_title.set(value);
                                                    set_form_error.set(None);
                                                })
                                                placeholder="Enter project title"
                                            />
                                        </FormField>
                                    }.into_any()
                                }
                            }}

                            <FormField
                                label="Description".to_string()
                                help_text="Optional project description".to_string()
                                required=false
                                has_error=false
                            >
                                <Input
                                    on_input=Callback::new(move |ev| {
                                        let value = event_target_value(&ev);
                                        set_project_description.set(value);
                                    })
                                    placeholder="Enter description"
                                />
                            </FormField>

                            <div class="flex gap-3 justify-end mt-4">
                                <Button
                                    on_click=Callback::new(move |_| set_show_create_modal.set(false))
                                >
                                    "Cancel"
                                </Button>
                                <Button button_type="submit">
                                    "Create Project"
                                </Button>
                            </div>
                        </div>
                    </form>
                </Modal>
            </Show>
        </div>
    }
}
