use leptos::prelude::*;
use leptos::task::spawn_local;
use crate::api::orchestrator::*;

#[component]
pub fn InfrastructurePage() -> impl IntoView {
    let (active_tab, set_active_tab) = signal("servers".to_string());
    let (tasks, tasks_loading, refresh_tasks) = use_tasks_list();
    let (system_health, health_loading, refresh_health) = use_system_health();
    let (show_create_modal, set_show_create_modal) = signal(false);
    let (show_batch_modal, set_show_batch_modal) = signal(false);

    view! {
        <div class="infrastructure-page h-full flex flex-col">
            // Header
            <div class="flex-none border-b border-base-300 p-4">
                <div class="flex items-center justify-between">
                    <h1 class="text-3xl font-bold">"Infrastructure Management"</h1>
                    <div class="flex gap-2">
                        <button
                            class="btn btn-outline btn-sm"
                            on:click=move |_| set_show_batch_modal.set(true)
                        >
                            "Batch Operations"
                        </button>
                        <button
                            class="btn btn-outline btn-sm"
                            on:click=move |_| refresh_health.dispatch(())
                            disabled=move || health_loading.get()
                        >
                            {move || if health_loading.get() { "Refreshing..." } else { "Refresh Status" }}
                        </button>
                        <button
                            class="btn btn-primary btn-sm"
                            on:click=move |_| set_show_create_modal.set(true)
                        >
                            "Create Workflow"
                        </button>
                    </div>
                </div>

                // Tab Navigation
                <div class="tabs tabs-boxed mt-4">
                    <a
                        class={move || if active_tab.get() == "servers" { "tab tab-active" } else { "tab" }}
                        on:click=move |_| set_active_tab.set("servers".to_string())
                    >
                        "Servers"
                    </a>
                    <a
                        class={move || if active_tab.get() == "workflows" { "tab tab-active" } else { "tab" }}
                        on:click=move |_| set_active_tab.set("workflows".to_string())
                    >
                        "Workflows"
                    </a>
                    <a
                        class={move || if active_tab.get() == "providers" { "tab tab-active" } else { "tab" }}
                        on:click=move |_| set_active_tab.set("providers".to_string())
                    >
                        "Providers"
                    </a>
                    <a
                        class={move || if active_tab.get() == "health" { "tab tab-active" } else { "tab" }}
                        on:click=move |_| set_active_tab.set("health".to_string())
                    >
                        "System Health"
                    </a>
                </div>
            </div>

            // Content Area
            <div class="flex-1 overflow-hidden">
                {move || match active_tab.get().as_str() {
                    "servers" => view! { <ServersTab /> }.into(),
                    "workflows" => view! { <WorkflowsTab tasks=tasks tasks_loading=tasks_loading refresh_tasks=refresh_tasks /> }.into(),
                    "providers" => view! { <ProvidersTab /> }.into(),
                    "health" => view! { <SystemHealthTab system_health=system_health health_loading=health_loading /> }.into(),
                    _ => view! { <div>"Unknown tab"</div> }.into(),
                }}
            </div>

            // Create Workflow Modal
            {move || if show_create_modal.get() {
                view! {
                    <CreateWorkflowModal
                        show=show_create_modal
                        set_show=set_show_create_modal
                    />
                }.into()
            } else {
                view! { <div></div> }.into()
            }}

            // Batch Operations Modal
            {move || if show_batch_modal.get() {
                view! {
                    <BatchWorkflowModal
                        show=show_batch_modal
                        set_show=set_show_batch_modal
                    />
                }.into()
            } else {
                view! { <div></div> }.into()
            }}
        </div>
    }
}

#[component]
fn ServersTab() -> impl IntoView {
    // Mock server data
    let servers = vec![
        Server {
            id: "s1".to_string(),
            name: "web-01".to_string(),
            status: "running".to_string(),
            ip_address: Some("192.168.1.10".to_string()),
            plan: "1xCPU-2GB".to_string(),
            zone: "de-fra1".to_string(),
        },
        Server {
            id: "s2".to_string(),
            name: "web-02".to_string(),
            status: "stopped".to_string(),
            ip_address: Some("192.168.1.11".to_string()),
            plan: "1xCPU-2GB".to_string(),
            zone: "us-nyc1".to_string(),
        },
    ];

    view! {
        <div class="p-4 h-full flex flex-col">
            <div class="flex-none mb-4 flex justify-between items-center">
                <h2 class="text-xl font-semibold">"Server Infrastructure"</h2>
                <div class="flex gap-2">
                    <input
                        type="text"
                        placeholder="Search servers..."
                        class="input input-bordered input-sm"
                    />
                    <select class="select select-bordered select-sm">
                        <option>"All Providers"</option>
                        <option>"UpCloud"</option>
                        <option>"AWS"</option>
                        <option>"Local"</option>
                    </select>
                </div>
            </div>

            <div class="flex-1 overflow-auto">
                <table class="table table-zebra w-full">
                    <thead>
                        <tr>
                            <th>"Name"</th>
                            <th>"Status"</th>
                            <th>"IP Address"</th>
                            <th>"Plan"</th>
                            <th>"Zone"</th>
                            <th>"Actions"</th>
                        </tr>
                    </thead>
                    <tbody>
                        {servers.into_iter().map(|server| {
                            view! {
                                <tr>
                                    <td class="font-medium">{&server.name}</td>
                                    <td>
                                        <div class={format!("badge {}",
                                            match server.status.as_str() {
                                                "running" => "badge-success",
                                                "stopped" => "badge-error",
                                                "starting" => "badge-warning",
                                                _ => "badge-ghost",
                                            }
                                        )}>
                                            {&server.status}
                                        </div>
                                    </td>
                                    <td class="font-mono text-sm">
                                        {server.ip_address.unwrap_or_else(|| "-".to_string())}
                                    </td>
                                    <td>{&server.plan}</td>
                                    <td>{&server.zone}</td>
                                    <td>
                                        <div class="flex gap-2">
                                            <button class="btn btn-ghost btn-xs">"SSH"</button>
                                            <button class="btn btn-ghost btn-xs">"Restart"</button>
                                            <button class="btn btn-ghost btn-xs text-error">"Delete"</button>
                                        </div>
                                    </td>
                                </tr>
                            }
                        }).collect::<Vec<_>>()}
                    </tbody>
                </table>
            </div>
        </div>
    }
}

#[component]
fn WorkflowsTab(
    tasks: ReadSignal<Vec<WorkflowTask>>,
    tasks_loading: ReadSignal<bool>,
    refresh_tasks: Action<(), ()>,
) -> impl IntoView {
    view! {
        <div class="p-4 h-full flex flex-col">
            <div class="flex-none mb-4 flex justify-between items-center">
                <h2 class="text-xl font-semibold">"Workflow Execution"</h2>
                <button
                    class="btn btn-outline btn-sm"
                    on:click=move |_| refresh_tasks.dispatch(())
                    disabled=move || tasks_loading.get()
                >
                    {move || if tasks_loading.get() { "Refreshing..." } else { "Refresh" }}
                </button>
            </div>

            <div class="flex-1 overflow-auto">
                {move || {
                    if tasks_loading.get() {
                        view! {
                            <div class="flex items-center justify-center h-32">
                                <span class="loading loading-spinner loading-md"></span>
                                <span class="ml-2">"Loading workflows..."</span>
                            </div>
                        }.into()
                    } else {
                        let task_list = tasks.get();
                        if task_list.is_empty() {
                            view! {
                                <div class="text-center text-base-content/50 mt-8">
                                    "No workflows found"
                                </div>
                            }.into()
                        } else {
                            view! {
                                <table class="table table-zebra w-full">
                                    <thead>
                                        <tr>
                                            <th>"ID"</th>
                                            <th>"Name"</th>
                                            <th>"Status"</th>
                                            <th>"Created"</th>
                                            <th>"Duration"</th>
                                            <th>"Actions"</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {task_list.into_iter().map(|task| {
                                            let task_id = task.id.clone();
                                            view! {
                                                <tr>
                                                    <td class="font-mono text-sm">{&task.id[..8]}"..."</td>
                                                    <td class="font-medium">{&task.name}</td>
                                                    <td>
                                                        <div class={format!("badge {}",
                                                            match task.status {
                                                                TaskStatus::Pending => "badge-warning",
                                                                TaskStatus::Running => "badge-info",
                                                                TaskStatus::Completed => "badge-success",
                                                                TaskStatus::Failed => "badge-error",
                                                                TaskStatus::Cancelled => "badge-ghost",
                                                            }
                                                        )}>
                                                            {format!("{:?}", task.status)}
                                                        </div>
                                                    </td>
                                                    <td class="text-sm text-base-content/70">
                                                        {&task.created_at}
                                                    </td>
                                                    <td class="text-sm">
                                                        {if let (Some(started), Some(completed)) = (&task.started_at, &task.completed_at) {
                                                            "2m 15s".to_string() // Calculate duration
                                                        } else if task.started_at.is_some() {
                                                            "Running...".to_string()
                                                        } else {
                                                            "-".to_string()
                                                        }}
                                                    </td>
                                                    <td>
                                                        <div class="flex gap-2">
                                                            <button class="btn btn-ghost btn-xs">"View"</button>
                                                            {if matches!(task.status, TaskStatus::Running | TaskStatus::Pending) {
                                                                view! {
                                                                    <button class="btn btn-ghost btn-xs text-error">"Cancel"</button>
                                                                }.into()
                                                            } else {
                                                                view! { <div></div> }.into()
                                                            }}
                                                        </div>
                                                    </td>
                                                </tr>
                                            }
                                        }).collect::<Vec<_>>()}
                                    </tbody>
                                </table>
                            }.into()
                        }
                    }
                }}
            </div>
        </div>
    }
}

#[component]
fn ProvidersTab() -> impl IntoView {
    let providers = vec![
        ("UpCloud", "Connected", "✅"),
        ("AWS", "Connected", "✅"),
        ("Local", "Available", "⚪"),
    ];

    view! {
        <div class="p-4">
            <h2 class="text-xl font-semibold mb-4">"Provider Credentials"</h2>

            <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {providers.into_iter().map(|(name, status, icon)| {
                    view! {
                        <div class="card bg-base-200 p-4">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3 class="font-semibold text-lg">{name}</h3>
                                    <p class="text-sm text-base-content/70">{status}</p>
                                </div>
                                <div class="text-2xl">{icon}</div>
                            </div>
                            <div class="mt-3 flex gap-2">
                                <button class="btn btn-outline btn-sm">"Configure"</button>
                                <button class="btn btn-ghost btn-sm">"Test"</button>
                            </div>
                        </div>
                    }
                }).collect::<Vec<_>>()}
            </div>

            <div class="mt-6">
                <button class="btn btn-primary btn-sm">"Add Provider"</button>
            </div>
        </div>
    }
}

#[component]
fn SystemHealthTab(
    system_health: ReadSignal<Option<serde_json::Value>>,
    health_loading: ReadSignal<bool>,
) -> impl IntoView {
    view! {
        <div class="p-4">
            <h2 class="text-xl font-semibold mb-4">"System Health Overview"</h2>

            {move || {
                if health_loading.get() {
                    view! {
                        <div class="flex items-center justify-center h-32">
                            <span class="loading loading-spinner loading-md"></span>
                            <span class="ml-2">"Loading health data..."</span>
                        </div>
                    }.into()
                } else if let Some(health_data) = system_health.get() {
                    view! {
                        <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                            <div class="card bg-base-200 p-4">
                                <h3 class="font-semibold">"Orchestrator"</h3>
                                <div class="badge badge-success mt-2">"Healthy"</div>
                                <p class="text-sm text-base-content/70 mt-2">"All systems operational"</p>
                            </div>

                            <div class="card bg-base-200 p-4">
                                <h3 class="font-semibold">"Database"</h3>
                                <div class="badge badge-success mt-2">"Connected"</div>
                                <p class="text-sm text-base-content/70 mt-2">"SurrealDB online"</p>
                            </div>

                            <div class="card bg-base-200 p-4">
                                <h3 class="font-semibold">"KMS"</h3>
                                <div class="badge badge-warning mt-2">"Limited"</div>
                                <p class="text-sm text-base-content/70 mt-2">"Local mode only"</p>
                            </div>

                            <div class="card bg-base-200 p-4">
                                <h3 class="font-semibold">"Policy Engine"</h3>
                                <div class="badge badge-success mt-2">"Active"</div>
                                <p class="text-sm text-base-content/70 mt-2">"Cedar engine operational"</p>
                            </div>

                            <div class="card bg-base-200 p-4">
                                <h3 class="font-semibold">"Providers"</h3>
                                <div class="badge badge-success mt-2">"2/3 Connected"</div>
                                <p class="text-sm text-base-content/70 mt-2">"UpCloud, AWS ready"</p>
                            </div>

                            <div class="card bg-base-200 p-4">
                                <h3 class="font-semibold">"Storage"</h3>
                                <div class="badge badge-success mt-2">"Available"</div>
                                <p class="text-sm text-base-content/70 mt-2">"85% capacity remaining"</p>
                            </div>
                        </div>
                    }.into()
                } else {
                    view! {
                        <div class="text-center text-base-content/50 mt-8">
                            "Failed to load health data"
                        </div>
                    }.into()
                }
            }}
        </div>
    }
}

#[component]
fn CreateWorkflowModal(
    show: ReadSignal<bool>,
    set_show: WriteSignal<bool>,
) -> impl IntoView {
    let (workflow_type, set_workflow_type) = signal("server".to_string());
    let (infra_name, set_infra_name) = signal("default".to_string());
    let (check_mode, set_check_mode) = signal(true);

    let create_workflow = move || {
        spawn_local(async move {
            let client = get_orchestrator_client();

            match workflow_type.get().as_str() {
                "server" => {
                    let workflow = CreateServerWorkflow {
                        infra: infra_name.get(),
                        settings: "default".to_string(),
                        servers: vec!["web-server".to_string()],
                        check_mode: check_mode.get(),
                        wait: false,
                    };

                    match client.create_server_workflow(workflow).await {
                        Ok(task_id) => {
                            logging::log!("Server workflow created: {}", task_id);
                            set_show.set(false);
                        }
                        Err(err) => {
                            logging::error!("Failed to create server workflow: {}", err);
                        }
                    }
                }
                "taskserv" => {
                    let workflow = TaskservWorkflow {
                        infra: infra_name.get(),
                        settings: "default".to_string(),
                        taskserv: "kubernetes".to_string(),
                        operation: "create".to_string(),
                        check_mode: check_mode.get(),
                        wait: false,
                    };

                    match client.create_taskserv_workflow(workflow).await {
                        Ok(task_id) => {
                            logging::log!("Taskserv workflow created: {}", task_id);
                            set_show.set(false);
                        }
                        Err(err) => {
                            logging::error!("Failed to create taskserv workflow: {}", err);
                        }
                    }
                }
                _ => {}
            }
        });
    };

    view! {
        <div class={move || if show.get() { "modal modal-open" } else { "modal" }}>
            <div class="modal-box">
                <h3 class="font-bold text-lg">"Create Workflow"</h3>

                <div class="py-4 space-y-4">
                    <div>
                        <label class="label">"Workflow Type"</label>
                        <select
                            class="select select-bordered w-full"
                            on:change=move |ev| set_workflow_type.set(event_target_value(&ev))
                        >
                            <option value="server">"Server Creation"</option>
                            <option value="taskserv">"Task Service"</option>
                            <option value="cluster">"Cluster"</option>
                        </select>
                    </div>

                    <div>
                        <label class="label">"Infrastructure"</label>
                        <input
                            type="text"
                            class="input input-bordered w-full"
                            prop:value=move || infra_name.get()
                            on:input=move |ev| set_infra_name.set(event_target_value(&ev))
                        />
                    </div>

                    <div>
                        <label class="label cursor-pointer">
                            <input
                                type="checkbox"
                                class="checkbox"
                                prop:checked=move || check_mode.get()
                                on:change=move |_| set_check_mode.set(!check_mode.get())
                            />
                            <span class="label-text">"Check mode (dry run)"</span>
                        </label>
                    </div>
                </div>

                <div class="modal-action">
                    <button
                        class="btn"
                        on:click=move |_| set_show.set(false)
                    >
                        "Cancel"
                    </button>
                    <button
                        class="btn btn-primary"
                        on:click=move |_| create_workflow()
                    >
                        "Create"
                    </button>
                </div>
            </div>
        </div>
    }
}

#[component]
fn BatchWorkflowModal(
    show: ReadSignal<bool>,
    set_show: WriteSignal<bool>,
) -> impl IntoView {
    let (batch_name, set_batch_name) = signal("multi_cloud_deployment".to_string());

    let create_batch_workflow = move || {
        spawn_local(async move {
            let client = get_orchestrator_client();

            let batch_workflow = BatchWorkflowRequest {
                workflow: BatchWorkflow {
                    name: batch_name.get(),
                    version: "1.0.0".to_string(),
                    storage_backend: "surrealdb".to_string(),
                    parallel_limit: 5,
                    rollback_enabled: true,
                    operations: vec![
                        BatchOperation {
                            id: "upcloud_servers".to_string(),
                            operation_type: "server_batch".to_string(),
                            provider: "upcloud".to_string(),
                            dependencies: vec![],
                            server_configs: Some(vec![
                                ServerConfig {
                                    name: "web-01".to_string(),
                                    plan: "1xCPU-2GB".to_string(),
                                    zone: "de-fra1".to_string(),
                                },
                                ServerConfig {
                                    name: "web-02".to_string(),
                                    plan: "1xCPU-2GB".to_string(),
                                    zone: "us-nyc1".to_string(),
                                },
                            ]),
                            taskservs: None,
                        },
                        BatchOperation {
                            id: "aws_taskservs".to_string(),
                            operation_type: "taskserv_batch".to_string(),
                            provider: "aws".to_string(),
                            dependencies: vec!["upcloud_servers".to_string()],
                            server_configs: None,
                            taskservs: Some(vec![
                                "kubernetes".to_string(),
                                "cilium".to_string(),
                                "containerd".to_string(),
                            ]),
                        },
                    ],
                },
            };

            match client.submit_batch_workflow(batch_workflow).await {
                Ok(batch_id) => {
                    logging::log!("Batch workflow created: {}", batch_id);
                    set_show.set(false);
                }
                Err(err) => {
                    logging::error!("Failed to create batch workflow: {}", err);
                }
            }
        });
    };

    view! {
        <div class={move || if show.get() { "modal modal-open" } else { "modal" }}>
            <div class="modal-box w-11/12 max-w-2xl">
                <h3 class="font-bold text-lg">"Create Batch Workflow"</h3>

                <div class="py-4 space-y-4">
                    <div>
                        <label class="label">"Batch Name"</label>
                        <input
                            type="text"
                            class="input input-bordered w-full"
                            prop:value=move || batch_name.get()
                            on:input=move |ev| set_batch_name.set(event_target_value(&ev))
                        />
                    </div>

                    <div>
                        <label class="label">"Operations"</label>
                        <div class="bg-base-200 p-4 rounded">
                            <div class="text-sm space-y-2">
                                <div>"1. Create UpCloud servers (web-01, web-02)"</div>
                                <div>"2. Deploy Kubernetes + Cilium + containerd on AWS"</div>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="label">"Parallel Limit"</label>
                            <input
                                type="number"
                                class="input input-bordered w-full"
                                value="5"
                                min="1"
                                max="20"
                            />
                        </div>
                        <div class="pt-8">
                            <label class="label cursor-pointer">
                                <input type="checkbox" class="checkbox" checked />
                                <span class="label-text">"Enable Rollback"</span>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="modal-action">
                    <button
                        class="btn"
                        on:click=move |_| set_show.set(false)
                    >
                        "Cancel"
                    </button>
                    <button
                        class="btn btn-primary"
                        on:click=move |_| create_batch_workflow()
                    >
                        "Create Batch"
                    </button>
                </div>
            </div>
        </div>
    }
}
