use leptos::prelude::*;
use leptos::task::spawn_local;
use serde::{Deserialize, Serialize};

use crate::components::LoadingSpinner;

/// Inference rule for infrastructure completion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferenceRule {
    pub id: String,
    pub name: String,
    pub organization: String,
    pub triggers: Vec<String>,
    pub inferences: Vec<RuleInference>,
    pub enabled: bool,
    pub priority: i32,
    pub created_at: String,
    pub updated_at: String,
}

/// Single inference in a rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleInference {
    pub technology: String,
    pub reason: String,
    pub confidence: f32,
    pub required: bool,
}

/// Rules Editor Page
#[component]
pub fn RulesEditorPage() -> impl IntoView {
    let (rules, set_rules) = signal::<Vec<InferenceRule>>(vec![]);
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal::<Option<String>>(None);
    let (show_form, set_show_form) = signal(false);
    let (form_name, set_form_name) = signal(String::new());
    let (form_org, set_form_org) = signal(String::new());

    Effect::new(move |_| {
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);
            match fetch_rules().await {
                Ok(results) => {
                    set_rules.set(results);
                }
                Err(e) => {
                    set_error.set(Some(format!("Failed to load rules: {}", e)));
                }
            }
            set_loading.set(false);
        });
    });

    view! {
        <div class="min-h-screen bg-base-200 p-6">
            <div class="container mx-auto">
                // Header
                <div class="mb-8">
                    <h1 class="text-4xl font-bold text-base-content mb-2">
                        "Inference Rules Editor"
                    </h1>
                    <p class="text-base-content/70">
                        "Create and manage infrastructure inference rules for your organization"
                    </p>
                </div>

                <div class="space-y-6">
                    // Action buttons
                    <div class="flex gap-3">
                        <button
                            on:click=move |_| set_show_form.set(!show_form.get())
                            class=format!("btn {}", if show_form.get() { "btn-error" } else { "btn-primary" })
                        >
                            {if show_form.get() { "Cancel" } else { "New Rule" }}
                        </button>
                    </div>

                    // Error display
                    <Show when=move || error.get().is_some()>
                        <div class="alert alert-error shadow-lg">
                            <div>
                                <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current flex-shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l-2-2m0 0l-2-2m2 2l2-2m-2 2l-2 2m8-8l-2 2m0 0l-2-2m2 2l2-2m-2 2l-2 2" />
                                </svg>
                                <span>{error.get().unwrap_or_default()}</span>
                            </div>
                        </div>
                    </Show>

                    // Rule form
                    <Show when=move || show_form.get()>
                        <div class="card bg-base-100 shadow-lg">
                            <div class="card-body">
                                <h2 class="card-title mb-4">"Create New Rule"</h2>
                                <div class="space-y-4">
                                    <div>
                                        <label class="label">
                                            <span class="label-text font-semibold">"Rule Name"</span>
                                        </label>
                                        <input
                                            type="text"
                                            on:input=move |ev| set_form_name.set(event_target_value(&ev))
                                            value=form_name
                                            class="input input-bordered w-full"
                                            placeholder="e.g., Django Backend Rule"
                                        />
                                    </div>

                                    <div>
                                        <label class="label">
                                            <span class="label-text font-semibold">"Organization"</span>
                                        </label>
                                        <input
                                            type="text"
                                            on:input=move |ev| set_form_org.set(event_target_value(&ev))
                                            value=form_org
                                            class="input input-bordered w-full"
                                            placeholder="e.g., default"
                                        />
                                    </div>

                                    <div class="alert alert-info">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current flex-shrink-0 w-6 h-6">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
                                        <span>"Add triggers and inferences after creating the rule"</span>
                                    </div>

                                    <div class="card-actions justify-end">
                                        <button
                                            on:click=move |_| set_show_form.set(false)
                                            class="btn btn-ghost"
                                        >
                                            "Cancel"
                                        </button>
                                        <button
                                            on:click=move |_| {
                                                // TODO: Call API to create rule
                                                set_show_form.set(false);
                                            }
                                            class="btn btn-primary"
                                            disabled=move || form_name.get().is_empty()
                                        >
                                            "Create"
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Show>

                    // Loading state
                    <Show when=move || loading.get()>
                        <div class="flex justify-center items-center py-12">
                            <LoadingSpinner size="loading-lg" />
                        </div>
                    </Show>

                    // Rules list
                    <Show when=move || !rules.get().is_empty()>
                        <div class="space-y-4">
                            {rules.get().into_iter().map(|rule| {
                                view! {
                                    <RuleListItem rule=rule />
                                }
                            }).collect_view()}
                        </div>
                    </Show>

                    <Show when=move || rules.get().is_empty() && !loading.get()>
                        <div class="alert">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current flex-shrink-0 w-6 h-6">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <span>"No rules defined. Create your first inference rule to extend infrastructure detection."</span>
                        </div>
                    </Show>
                </div>
            </div>
        </div>
    }
}

/// Rule list item component
#[component]
pub fn RuleListItem(rule: InferenceRule) -> impl IntoView {
    let rule_triggers = rule.triggers.clone();
    let rule_inferences = rule.inferences.clone();

    view! {
        <div class="card bg-base-100 shadow-md hover:shadow-lg transition-shadow">
            <div class="card-body">
                <div class="flex justify-between items-start">
                    <div class="flex-1">
                        <h3 class="card-title">{rule.name.clone()}</h3>
                        <p class="text-sm text-base-content/60 mb-4">{rule.organization.clone()}</p>

                        <div class="space-y-3">
                            {if !rule_triggers.is_empty() {
                                view! {
                                    <div>
                                        <p class="text-sm font-semibold mb-2">"Triggers ("  {rule_triggers.len()} ")"</p>
                                        <div class="flex flex-wrap gap-2">
                                            {rule_triggers.iter().take(3).map(|t| {
                                                let t = t.clone();
                                                view! {
                                                    <span class="badge badge-warning">{t}</span>
                                                }
                                            }).collect_view()}
                                            {if rule_triggers.len() > 3 {
                                                view! {
                                                    <span class="badge badge-ghost">
                                                        "+" {rule_triggers.len() - 3}
                                                    </span>
                                                }.into_any()
                                            } else {
                                                ().into_any()
                                            }}
                                        </div>
                                    </div>
                                }.into_any()
                            } else {
                                ().into_any()
                            }}

                            {if !rule_inferences.is_empty() {
                                view! {
                                    <div>
                                        <p class="text-sm font-semibold mb-2">"Inferences (" {rule_inferences.len()} ")"</p>
                                        <div class="flex flex-wrap gap-2">
                                            {rule_inferences.iter().take(3).map(|inf| {
                                                view! {
                                                    <span class="badge badge-info">
                                                        {inf.technology.clone()}
                                                    </span>
                                                }
                                            }).collect_view()}
                                            {if rule_inferences.len() > 3 {
                                                view! {
                                                    <span class="badge badge-ghost">
                                                        "+" {rule_inferences.len() - 3}
                                                    </span>
                                                }.into_any()
                                            } else {
                                                ().into_any()
                                            }}
                                        </div>
                                    </div>
                                }.into_any()
                            } else {
                                ().into_any()
                            }}
                        </div>
                    </div>

                    <div class="flex items-start gap-2 ml-4">
                        <div class="badge" class:badge-success={rule.enabled} class:badge-ghost={!rule.enabled}>
                            {if rule.enabled { "Enabled" } else { "Disabled" }}
                        </div>
                        <button class="btn btn-ghost btn-sm">"Edit"</button>
                        <button class="btn btn-ghost btn-sm text-error">"Delete"</button>
                    </div>
                </div>
            </div>
        </div>
    }
}

/// Placeholder API call
async fn fetch_rules() -> Result<Vec<InferenceRule>, String> {
    // TODO: Replace with actual API call once backend endpoint is ready
    Ok(vec![])
}
