use leptos::prelude::*;
use leptos_router::hooks::use_navigate;
use serde::{Deserialize, Serialize};
use wasm_bindgen::JsCast;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionCard {
    pub id: String,
    pub title: String,
    pub description: String,
    pub icon: String,
    pub button_text: String,
    pub action_type: ActionType,
    pub action_data: String,
    pub priority: usize,
    pub completed: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ActionType {
    Navigate,   // Navigate to a page
    OpenForm,   // Open a modal form
    RunCommand, // Execute a command
    OpenDocs,   // Open documentation
}

#[component]
pub fn NextSteps(
    #[prop(into, optional)] workspace_exists: Signal<bool>,
    #[prop(into, optional)] servers_exist: Signal<bool>,
    #[prop(into, optional)] taskservs_exist: Signal<bool>,
) -> impl IntoView {
    let (selected_action, set_selected_action) = signal(None::<String>);

    let action_cards = move || {
        let mut cards = vec![];

        // Create workspace if none exists
        if !workspace_exists.get() {
            cards.push(ActionCard {
                id: "create-workspace".to_string(),
                title: "Create Your First Workspace".to_string(),
                description: "Set up a workspace to organize your infrastructure configurations \
                              and state."
                    .to_string(),
                icon: "📁".to_string(),
                button_text: "Create Workspace".to_string(),
                action_type: ActionType::OpenForm,
                action_data: "workspace-form".to_string(),
                priority: 1,
                completed: false,
            });
        }

        // Deploy servers if workspace exists but no servers
        if workspace_exists.get() && !servers_exist.get() {
            cards.push(ActionCard {
                id: "deploy-servers".to_string(),
                title: "Deploy Your First Server".to_string(),
                description: "Create cloud servers to host your infrastructure services."
                    .to_string(),
                icon: "🖥️".to_string(),
                button_text: "Deploy Server".to_string(),
                action_type: ActionType::Navigate,
                action_data: "/servers".to_string(),
                priority: 2,
                completed: false,
            });
        }

        // Install Kubernetes if servers exist but no taskservs
        if servers_exist.get() && !taskservs_exist.get() {
            cards.push(ActionCard {
                id: "install-kubernetes".to_string(),
                title: "Install Kubernetes".to_string(),
                description: "Set up Kubernetes cluster for container orchestration.".to_string(),
                icon: "☸️".to_string(),
                button_text: "Install Kubernetes".to_string(),
                action_type: ActionType::Navigate,
                action_data: "/taskservs".to_string(),
                priority: 3,
                completed: false,
            });
        }

        // Always show these common actions
        cards.push(ActionCard {
            id: "view-workflows".to_string(),
            title: "Monitor Workflows".to_string(),
            description: "Track ongoing deployments and infrastructure changes.".to_string(),
            icon: "🔄".to_string(),
            button_text: "View Workflows".to_string(),
            action_type: ActionType::Navigate,
            action_data: "/workflows".to_string(),
            priority: 4,
            completed: false,
        });

        cards.push(ActionCard {
            id: "read-docs".to_string(),
            title: "Explore Documentation".to_string(),
            description: "Learn about features, best practices, and advanced configurations."
                .to_string(),
            icon: "📚".to_string(),
            button_text: "Read Docs".to_string(),
            action_type: ActionType::OpenDocs,
            action_data: "quickstart".to_string(),
            priority: 5,
            completed: false,
        });

        cards.push(ActionCard {
            id: "configure-settings".to_string(),
            title: "Configure Settings".to_string(),
            description: "Customize your platform configuration and preferences.".to_string(),
            icon: "⚙️".to_string(),
            button_text: "Open Settings".to_string(),
            action_type: ActionType::Navigate,
            action_data: "/settings".to_string(),
            priority: 6,
            completed: false,
        });

        // Sort by priority
        cards.sort_by_key(|c| c.priority);
        cards
    };

    let handle_action = move |card: ActionCard| {
        match card.action_type {
            ActionType::Navigate => {
                // Use Leptos router to navigate
                let navigate = use_navigate();
                navigate(&card.action_data, Default::default());
            }
            ActionType::OpenForm => {
                set_selected_action.set(Some(card.id));
                web_sys::console::log_1(&format!("Opening form: {}", card.action_data).into());
            }
            ActionType::RunCommand => {
                web_sys::console::log_1(&format!("Running command: {}", card.action_data).into());
                // TODO: Implement command execution
            }
            ActionType::OpenDocs => {
                // Open documentation in new tab
                if let Some(window) = web_sys::window() {
                    let _ = window
                        .open_with_url_and_target(&format!("/docs/{}", card.action_data), "_blank");
                }
            }
        }
    };

    view! {
        <div class="next-steps" style="padding: 20px;">
            <div style="margin-bottom: 20px;">
                <h2 style="margin: 0 0 10px 0; font-size: 1.5rem; color: #1f2937;">
                    "Next Steps"
                </h2>
                <p style="margin: 0; color: #6b7280; line-height: 1.6;">
                    "Here are recommended actions based on your current setup. Complete these to get the most out of your platform."
                </p>
            </div>

            <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px;">
                {move || action_cards().into_iter().map(|card| {
                    let card_clone = card.clone();
                    let card_clone2 = card.clone();

                    view! {
                        <div
                            class="action-card"
                            style="background: white; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow: hidden; transition: all 0.2s; border-top: 4px solid #3b82f6;"
                            on:mouseenter=move |_| {
                                // Add hover effect
                            }
                        >
                            <div style="padding: 24px;">
                                // Icon and title
                                <div style="display: flex; align-items: start; gap: 15px; margin-bottom: 15px;">
                                    <div style="font-size: 2.5rem; line-height: 1;">
                                        {card_clone2.icon}
                                    </div>
                                    <div style="flex: 1;">
                                        <h3 style="margin: 0 0 8px 0; font-size: 1.15rem; color: #1f2937; font-weight: 600;">
                                            {card_clone2.title}
                                        </h3>
                                        <p style="margin: 0; color: #6b7280; font-size: 0.9rem; line-height: 1.5;">
                                            {card_clone2.description}
                                        </p>
                                    </div>
                                </div>

                                // Action button
                                <button
                                    on:click=move |_| handle_action(card.clone())
                                    style="width: 100%; padding: 12px 20px; background: #3b82f6; color: white; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.95rem; transition: background 0.2s;"
                                    on:mouseenter=move |ev| {
                                        if let Some(target) = ev.target() {
                                            if let Ok(element) = target.dyn_into::<web_sys::HtmlElement>() {
                                                let _ = element.style().set_property("background", "#2563eb");
                                            }
                                        }
                                    }
                                    on:mouseleave=move |ev| {
                                        if let Some(target) = ev.target() {
                                            if let Ok(element) = target.dyn_into::<web_sys::HtmlElement>() {
                                                let _ = element.style().set_property("background", "#3b82f6");
                                            }
                                        }
                                    }
                                >
                                    {card_clone.button_text}
                                </button>

                                // Priority badge
                                <div style="margin-top: 12px; display: flex; justify-content: space-between; align-items: center;">
                                    <span style=format!(
                                        "background: {}; color: white; padding: 4px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 600;",
                                        match card_clone.priority {
                                            1..=2 => "#ef4444",
                                            3..=4 => "#f59e0b",
                                            _ => "#6b7280",
                                        }
                                    )>
                                        {match card_clone.priority {
                                            1..=2 => "High Priority",
                                            3..=4 => "Medium Priority",
                                            _ => "Optional",
                                        }}
                                    </span>

                                    // Documentation link
                                    <a
                                        href="#"
                                        style="color: #3b82f6; font-size: 0.85rem; text-decoration: none; font-weight: 500;"
                                        on:click=move |ev| {
                                            ev.prevent_default();
                                            web_sys::console::log_1(&"Opening docs".into());
                                        }
                                    >
                                        "Learn more →"
                                    </a>
                                </div>
                            </div>
                        </div>
                    }
                }).collect_view()}
            </div>

            // Help section
            <div style="margin-top: 30px; background: #f0fdf4; border: 1px solid #86efac; border-left: 4px solid #10b981; padding: 20px; border-radius: 8px;">
                <div style="display: flex; align-items: start; gap: 15px;">
                    <div style="font-size: 2rem;">
                        "💡"
                    </div>
                    <div>
                        <h4 style="margin: 0 0 10px 0; color: #166534; font-size: 1.1rem; font-weight: 600;">
                            "Need Help?"
                        </h4>
                        <p style="margin: 0 0 12px 0; color: #15803d; line-height: 1.6;">
                            "Check out these resources to learn more about the platform:"
                        </p>
                        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                            <a
                                href="/docs/quickstart"
                                target="_blank"
                                style="padding: 8px 16px; background: white; color: #166534; border: 1px solid #86efac; text-decoration: none; border-radius: 6px; font-weight: 500; font-size: 0.9rem;"
                            >
                                "📚 Quick Start Guide"
                            </a>
                            <a
                                href="/docs/architecture"
                                target="_blank"
                                style="padding: 8px 16px; background: white; color: #166534; border: 1px solid #86efac; text-decoration: none; border-radius: 6px; font-weight: 500; font-size: 0.9rem;"
                            >
                                "🏗️ Architecture Overview"
                            </a>
                            <a
                                href="/docs/troubleshooting"
                                target="_blank"
                                style="padding: 8px 16px; background: white; color: #166534; border: 1px solid #86efac; text-decoration: none; border-radius: 6px; font-weight: 500; font-size: 0.9rem;"
                            >
                                "🔧 Troubleshooting"
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }
}

/// Standalone component for a single action card
#[component]
pub fn ActionCardComponent(
    card: ActionCard,
    #[prop(into)] on_action: Callback<ActionCard>,
) -> impl IntoView {
    let card_clone = card.clone();

    view! {
        <div
            class="action-card"
            style="background: white; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 20px; transition: transform 0.2s, box-shadow 0.2s;"
        >
            <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                <div style="font-size: 2rem;">
                    {card.icon}
                </div>
                <h3 style="margin: 0; font-size: 1.1rem; color: #1f2937; flex: 1;">
                    {card.title}
                </h3>
            </div>

            <p style="margin: 0 0 15px 0; color: #6b7280; font-size: 0.9rem; line-height: 1.5;">
                {card.description}
            </p>

            <button
                on:click=move |_| on_action.run(card_clone.clone())
                style="width: 100%; padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 6px; font-weight: 600; cursor: pointer;"
            >
                {card.button_text}
            </button>
        </div>
    }
}
