//! Server config page component.

use leptos::prelude::*;

use crate::components::{Card, MessageAlert, PageHeader};
use crate::hooks::use_fetch;
use crate::models::ServerConfig;

/// Config page component.
#[component]
pub fn ConfigPage() -> impl IntoView {
    let (message, set_message) = signal(Option::<(String, bool)>::None);
    let (pending, set_pending) = signal(false);

    let config = use_fetch::<ServerConfig>(|| "/api/admin/config".to_string());

    view! {
        <PageHeader
            title="Server Configuration"
            subtitle="Manage global server settings"
        />

        <Suspense fallback=|| view! { <p>"Loading configuration..."</p> }>
            {move || {
                config.get().map(|maybe_config| {
                    match maybe_config {
                        Some(cfg) => view! {
                            <ConfigForm config=cfg message=message set_message=set_message pending=pending set_pending=set_pending />
                        }.into_any(),
                        None => view! {
                            <Card>
                                <p class="text-error">"Failed to load configuration. You may not have permission to access this page."</p>
                            </Card>
                        }.into_any()
                    }
                })
            }}
        </Suspense>
    }
}

/// Config form component.
#[component]
#[allow(unused_variables)]
fn ConfigForm(
    config: ServerConfig,
    message: ReadSignal<Option<(String, bool)>>,
    set_message: WriteSignal<Option<(String, bool)>>,
    pending: ReadSignal<bool>,
    set_pending: WriteSignal<bool>,
) -> impl IntoView {
    let (name, set_name) = signal(config.name.clone());
    let (description, set_description) = signal(config.description.clone().unwrap_or_default());
    let (welcome_message, set_welcome_message) =
        signal(config.welcome_message.clone().unwrap_or_default());
    let (max_users_per_channel, set_max_users_per_channel) = signal(config.max_users_per_channel);
    let (message_rate_limit, set_message_rate_limit) = signal(config.message_rate_limit);
    let (message_rate_window_seconds, set_message_rate_window_seconds) =
        signal(config.message_rate_window_seconds);
    let (allow_guest_access, set_allow_guest_access) = signal(config.allow_guest_access);
    let (allow_user_uploads, set_allow_user_uploads) = signal(config.allow_user_uploads);
    let (require_email_verification, set_require_email_verification) =
        signal(config.require_email_verification);

    let on_submit = move |ev: leptos::ev::SubmitEvent| {
        ev.prevent_default();
        set_pending.set(true);
        set_message.set(None);

        #[cfg(feature = "hydrate")]
        {
            use gloo_net::http::Request;
            use leptos::task::spawn_local;

            let data = serde_json::json!({
                "name": name.get(),
                "description": if description.get().is_empty() { None::<String> } else { Some(description.get()) },
                "welcome_message": if welcome_message.get().is_empty() { None::<String> } else { Some(welcome_message.get()) },
                "max_users_per_channel": max_users_per_channel.get(),
                "message_rate_limit": message_rate_limit.get(),
                "message_rate_window_seconds": message_rate_window_seconds.get(),
                "allow_guest_access": allow_guest_access.get(),
                "allow_user_uploads": allow_user_uploads.get(),
                "require_email_verification": require_email_verification.get()
            });

            spawn_local(async move {
                let response = Request::put("/api/admin/config")
                    .json(&data)
                    .unwrap()
                    .send()
                    .await;

                set_pending.set(false);

                match response {
                    Ok(resp) if resp.ok() => {
                        set_message.set(Some((
                            "Configuration saved successfully!".to_string(),
                            true,
                        )));
                    }
                    Ok(_) => {
                        set_message.set(Some(("Failed to save configuration".to_string(), false)));
                    }
                    Err(_) => {
                        set_message.set(Some(("Network error".to_string(), false)));
                    }
                }
            });
        }
    };

    view! {
        <Card>
            <form on:submit=on_submit class="config-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="name" class="form-label">"Server Name"</label>
                        <input
                            type="text"
                            id="name"
                            required=true
                            class="form-input"
                            prop:value=move || name.get()
                            on:input=move |ev| set_name.set(event_target_value(&ev))
                        />
                    </div>
                </div>

                <div class="form-group">
                    <label for="description" class="form-label">"Server Description"</label>
                    <textarea
                        id="description"
                        class="form-textarea"
                        prop:value=move || description.get()
                        on:input=move |ev| set_description.set(event_target_value(&ev))
                    ></textarea>
                </div>

                <div class="form-group">
                    <label for="welcome_message" class="form-label">"Welcome Message"</label>
                    <textarea
                        id="welcome_message"
                        class="form-textarea"
                        prop:value=move || welcome_message.get()
                        on:input=move |ev| set_welcome_message.set(event_target_value(&ev))
                    ></textarea>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="max_users_per_channel" class="form-label">"Max Users per Channel"</label>
                        <input
                            type="number"
                            id="max_users_per_channel"
                            min="1"
                            max="1000"
                            class="form-input"
                            prop:value=move || max_users_per_channel.get()
                            on:input=move |ev| {
                                if let Ok(v) = event_target_value(&ev).parse() {
                                    set_max_users_per_channel.set(v);
                                }
                            }
                        />
                    </div>
                    <div class="form-group">
                        <label for="message_rate_limit" class="form-label">"Message Rate Limit"</label>
                        <input
                            type="number"
                            id="message_rate_limit"
                            min="1"
                            max="100"
                            class="form-input"
                            prop:value=move || message_rate_limit.get()
                            on:input=move |ev| {
                                if let Ok(v) = event_target_value(&ev).parse() {
                                    set_message_rate_limit.set(v);
                                }
                            }
                        />
                    </div>
                    <div class="form-group">
                        <label for="message_rate_window_seconds" class="form-label">"Rate Window (seconds)"</label>
                        <input
                            type="number"
                            id="message_rate_window_seconds"
                            min="1"
                            max="300"
                            class="form-input"
                            prop:value=move || message_rate_window_seconds.get()
                            on:input=move |ev| {
                                if let Ok(v) = event_target_value(&ev).parse() {
                                    set_message_rate_window_seconds.set(v);
                                }
                            }
                        />
                    </div>
                </div>

                <div class="checkbox-group">
                    <label class="checkbox-label">
                        <input
                            type="checkbox"
                            class="form-checkbox"
                            prop:checked=move || allow_guest_access.get()
                            on:change=move |ev| set_allow_guest_access.set(event_target_checked(&ev))
                        />
                        "Allow Guest Access"
                    </label>
                </div>

                <div class="checkbox-group">
                    <label class="checkbox-label">
                        <input
                            type="checkbox"
                            class="form-checkbox"
                            prop:checked=move || allow_user_uploads.get()
                            on:change=move |ev| set_allow_user_uploads.set(event_target_checked(&ev))
                        />
                        "Allow User Uploads"
                    </label>
                </div>

                <div class="checkbox-group">
                    <label class="checkbox-label">
                        <input
                            type="checkbox"
                            class="form-checkbox"
                            prop:checked=move || require_email_verification.get()
                            on:change=move |ev| set_require_email_verification.set(event_target_checked(&ev))
                        />
                        "Require Email Verification"
                    </label>
                </div>

                <MessageAlert message=message />

                <div class="form-actions">
                    <button
                        type="submit"
                        class="btn btn-primary"
                        disabled=move || pending.get()
                    >
                        {move || if pending.get() { "Saving..." } else { "Save Configuration" }}
                    </button>
                </div>
            </form>
        </Card>
    }
}
