use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::hooks::use_navigate;
use crate::services::auth_service::{AuthService, LoginResponse};
use crate::types::auth::AuthTokens;

#[derive(Clone, Copy, Debug, PartialEq)]
enum LoginStep {
    Credentials,
    MfaVerification,
}

#[component]
pub fn LoginFormMfa() -> impl IntoView {
    let (step, set_step) = signal(LoginStep::Credentials);
    let (username, set_username) = signal(String::new());
    let (password, set_password) = signal(String::new());
    let (mfa_code, set_mfa_code) = signal(String::new());
    let (partial_token, set_partial_token) = signal(None::<String>);
    let (error_message, set_error_message) = signal(None::<String>);
    let (loading, set_loading) = signal(false);

    let navigate = use_navigate();
    let auth_service = AuthService::new();

    // Handle credentials submission
    let handle_credentials_submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();
        set_loading.set(true);
        set_error_message.set(None);

        let auth_service = auth_service.clone();
        let username_val = username.get();
        let password_val = password.get();

        spawn_local(async move {
            match auth_service.login(username_val, password_val).await {
                Ok(response) => {
                    if response.requires_mfa {
                        // MFA required - move to verification step
                        set_partial_token.set(response.partial_token);
                        set_step.set(LoginStep::MfaVerification);
                    } else {
                        // No MFA - direct login success
                        if let Some(tokens) = response.tokens {
                            handle_login_success(tokens, navigate);
                        }
                    }
                }
                Err(e) => {
                    set_error_message.set(Some(format!("Login failed: {}", e)));
                }
            }
            set_loading.set(false);
        });
    };

    // Handle MFA code submission
    let handle_mfa_submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();
        set_loading.set(true);
        set_error_message.set(None);

        let auth_service = auth_service.clone();
        let code = mfa_code.get();
        let token = partial_token.get().unwrap_or_default();

        spawn_local(async move {
            match auth_service.complete_mfa_login(token, code).await {
                Ok(tokens) => {
                    handle_login_success(tokens, navigate);
                }
                Err(e) => {
                    set_error_message.set(Some(format!("MFA verification failed: {}", e)));
                }
            }
            set_loading.set(false);
        });
    };

    view! {
        <div class="min-h-screen flex items-center justify-center bg-base-200 py-12 px-4 sm:px-6 lg:px-8">
            <div class="max-w-md w-full space-y-8">
                // Header
                <div class="text-center">
                    <h2 class="text-3xl font-extrabold text-base-content">
                        {move || if step.get() == LoginStep::Credentials {
                            "Sign in to Control Center"
                        } else {
                            "Two-Factor Authentication"
                        }}
                    </h2>
                    <p class="mt-2 text-sm text-base-content/70">
                        {move || if step.get() == LoginStep::Credentials {
                            "Enter your credentials to continue"
                        } else {
                            "Enter the verification code from your authenticator app"
                        }}
                    </p>
                </div>

                // Error alert
                {move || error_message.get().map(|err| view! {
                    <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 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <span>{err}</span>
                        </div>
                    </div>
                })}

                // Credentials form
                <Show
                    when=move || step.get() == LoginStep::Credentials
                    fallback=|| view! { <div></div> }
                >
                    <form on:submit=handle_credentials_submit class="mt-8 space-y-6 card bg-base-100 shadow-xl p-8">
                        <div class="form-control">
                            <label class="label" for="username">
                                <span class="label-text font-medium">"Username or Email"</span>
                            </label>
                            <input
                                type="text"
                                id="username"
                                class="input input-bordered w-full"
                                placeholder="Enter your username or email"
                                required
                                on:input=move |ev| {
                                    set_username.set(event_target_value(&ev));
                                }
                                prop:value=username
                            />
                        </div>

                        <div class="form-control">
                            <label class="label" for="password">
                                <span class="label-text font-medium">"Password"</span>
                            </label>
                            <input
                                type="password"
                                id="password"
                                class="input input-bordered w-full"
                                placeholder="Enter your password"
                                required
                                on:input=move |ev| {
                                    set_password.set(event_target_value(&ev));
                                }
                                prop:value=password
                            />
                        </div>

                        <div class="flex items-center justify-between">
                            <label class="label cursor-pointer">
                                <input type="checkbox" class="checkbox checkbox-primary checkbox-sm" />
                                <span class="label-text ml-2">"Remember me"</span>
                            </label>
                            <a href="#" class="text-sm link link-primary">
                                "Forgot password?"
                            </a>
                        </div>

                        <button
                            type="submit"
                            class="btn btn-primary w-full"
                            disabled=move || loading.get()
                        >
                            {move || if loading.get() {
                                view! {
                                    <span class="loading loading-spinner loading-sm"></span>
                                    " Signing in..."
                                }.into_view()
                            } else {
                                view! { "Sign In" }.into_view()
                            }}
                        </button>
                    </form>
                </Show>

                // MFA verification form
                <Show
                    when=move || step.get() == LoginStep::MfaVerification
                    fallback=|| view! { <div></div> }
                >
                    <form on:submit=handle_mfa_submit class="mt-8 space-y-6 card bg-base-100 shadow-xl p-8">
                        <div class="text-center mb-4">
                            <div class="inline-flex items-center justify-center w-16 h-16 bg-primary/10 rounded-full mb-4">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                                </svg>
                            </div>
                        </div>

                        <div class="form-control">
                            <label class="label" for="mfa-code">
                                <span class="label-text font-medium">"Verification Code"</span>
                            </label>
                            <input
                                type="text"
                                id="mfa-code"
                                class="input input-bordered w-full text-center text-2xl tracking-widest"
                                placeholder="000000"
                                maxlength="6"
                                pattern="[0-9]{6}"
                                required
                                on:input=move |ev| {
                                    set_mfa_code.set(event_target_value(&ev));
                                }
                                prop:value=mfa_code
                            />
                            <label class="label">
                                <span class="label-text-alt">"Enter the 6-digit code from your authenticator app"</span>
                            </label>
                        </div>

                        <button
                            type="submit"
                            class="btn btn-primary w-full"
                            disabled=move || loading.get()
                        >
                            {move || if loading.get() {
                                view! {
                                    <span class="loading loading-spinner loading-sm"></span>
                                    " Verifying..."
                                }.into_view()
                            } else {
                                view! { "Verify" }.into_view()
                            }}
                        </button>

                        <button
                            type="button"
                            class="btn btn-ghost w-full"
                            on:click=move |_| {
                                set_step.set(LoginStep::Credentials);
                                set_mfa_code.set(String::new());
                                set_error_message.set(None);
                            }
                        >
                            "Back to login"
                        </button>

                        <div class="divider">"OR"</div>

                        <div class="text-center">
                            <p class="text-sm text-base-content/70 mb-2">"Lost access to your device?"</p>
                            <button type="button" class="btn btn-sm btn-outline">
                                "Use backup code"
                            </button>
                        </div>
                    </form>
                </Show>

                // Footer
                <div class="text-center text-sm text-base-content/70">
                    <p>
                        "Need help? "
                        <a href="#" class="link link-primary">"Contact support"</a>
                    </p>
                </div>
            </div>
        </div>
    }
}

fn handle_login_success(tokens: AuthTokens, navigate: leptos_router::NavigateFunction) {
    // Store tokens (already done in auth_service)
    // Navigate to dashboard
    navigate("/dashboard", Default::default());
}
