use dioxus::prelude::*;

use crate::components::{MemberRow, PageHeader};
use crate::i18n::{t, tw, Locale};
use crate::infrastructure::litellm::get_litellm_usage;
use crate::models::{BillingUsage, LitellmUsageStats, MemberRole, OrgMember};

/// Organization dashboard with billing stats, member table, and invite modal.
///
/// Shows current billing usage (fetched from LiteLLM), a per-model
/// breakdown table, a table of organization members with role
/// management, and a button to invite new members.
#[component]
pub fn OrgDashboardPage() -> Element {
    let locale = use_context::<Signal<Locale>>();
    let l = *locale.read();

    let members = use_signal(mock_members);
    let usage = mock_usage();
    let mut show_invite = use_signal(|| false);
    let mut invite_email = use_signal(String::new);

    let members_list = members.read().clone();

    // Compute date range: 1st of current month to today
    let (start_date, end_date) = current_month_range();

    // Fetch real usage stats from LiteLLM via server function.
    // use_resource memoises and won't re-fire on parent re-renders.
    let usage_resource = use_resource(move || {
        let start = start_date.clone();
        let end = end_date.clone();
        async move { get_litellm_usage(start, end).await }
    });

    // Clone out of Signal to avoid holding the borrow across rsx!
    let usage_snapshot = usage_resource.read().clone();

    // Format token counts for display
    let tokens_display = format_tokens(usage.tokens_used);
    let tokens_limit_display = format_tokens(usage.tokens_limit);

    rsx! {
        section { class: "org-dashboard-page",
            PageHeader {
                title: t(l, "org.title"),
                subtitle: t(l, "org.subtitle"),
                actions: rsx! {
                    button {
                        class: "btn-primary",
                        onclick: move |_| show_invite.set(true),
                        {t(l, "org.invite_member")}
                    }
                },
            }

            // Stats bar
            div { class: "org-stats-bar",
                div { class: "org-stat",
                    span { class: "org-stat-value",
                        "{usage.seats_used}/{usage.seats_total}"
                    }
                    span { class: "org-stat-label", {t(l, "org.seats_used")} }
                }
                div { class: "org-stat",
                    span { class: "org-stat-value", "{tokens_display}" }
                    span { class: "org-stat-label",
                        {tw(l, "org.of_tokens", &[("limit", &tokens_limit_display)])}
                    }
                }
                div { class: "org-stat",
                    span { class: "org-stat-value",
                        "{usage.billing_cycle_end}"
                    }
                    span { class: "org-stat-label", {t(l, "org.cycle_ends")} }
                }
            }

            // LiteLLM usage stats section
            {render_usage_section(l, &usage_snapshot)}

            // Members table
            div { class: "org-table-wrapper",
                table { class: "org-table",
                    thead {
                        tr {
                            th { {t(l, "org.name")} }
                            th { {t(l, "org.email")} }
                            th { {t(l, "org.role")} }
                            th { {t(l, "org.joined")} }
                        }
                    }
                    tbody {
                        for member in members_list {
                            MemberRow {
                                key: "{member.id}",
                                member,
                                on_role_change: move |_| {},
                            }
                        }
                    }
                }
            }

            // Invite modal
            if *show_invite.read() {
                div {
                    class: "modal-overlay",
                    onclick: move |_| show_invite.set(false),
                    div {
                        class: "modal-content",
                        // Prevent clicks inside modal from closing it
                        onclick: move |evt: Event<MouseData>| evt.stop_propagation(),
                        h3 { {t(l, "org.invite_title")} }
                        div { class: "form-group",
                            label { {t(l, "org.email_address")} }
                            input {
                                class: "form-input",
                                r#type: "email",
                                placeholder: t(l, "org.email_placeholder"),
                                value: "{invite_email}",
                                oninput: move |evt: Event<FormData>| {
                                    invite_email.set(evt.value());
                                },
                            }
                        }
                        div { class: "modal-actions",
                            button {
                                class: "btn-secondary",
                                onclick: move |_| show_invite.set(false),
                                {t(l, "common.cancel")}
                            }
                            button {
                                class: "btn-primary",
                                onclick: move |_| show_invite.set(false),
                                {t(l, "org.send_invite")}
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Render the LiteLLM usage stats section: totals bar + per-model table.
///
/// Shows a loading state while the resource is pending, an error/empty
/// message on failure, and the full breakdown on success.
fn render_usage_section(
    l: Locale,
    snapshot: &Option<Result<LitellmUsageStats, ServerFnError>>,
) -> Element {
    match snapshot {
        None => rsx! {
            div { class: "org-usage-loading",
                span { {t(l, "org.loading_usage")} }
            }
        },
        Some(Err(_)) => rsx! {
            div { class: "org-usage-unavailable",
                span { {t(l, "org.usage_unavailable")} }
            }
        },
        Some(Ok(stats)) if stats.total_tokens == 0 && stats.model_breakdown.is_empty() => {
            rsx! {
                div { class: "org-usage-unavailable",
                    span { {t(l, "org.usage_unavailable")} }
                }
            }
        }
        Some(Ok(stats)) => {
            let spend_display = format!("${:.2}", stats.total_spend);
            let total_display = format_tokens(stats.total_tokens);
            // Free-tier LiteLLM doesn't provide prompt/completion split
            let has_token_split =
                stats.total_prompt_tokens > 0 || stats.total_completion_tokens > 0;

            rsx! {
                // Usage totals bar
                div { class: "org-stats-bar",
                    div { class: "org-stat",
                        span { class: "org-stat-value", "{spend_display}" }
                        span { class: "org-stat-label",
                            {t(l, "org.total_spend")}
                        }
                    }
                    div { class: "org-stat",
                        span { class: "org-stat-value",
                            "{total_display}"
                        }
                        span { class: "org-stat-label",
                            {t(l, "org.total_tokens")}
                        }
                    }
                    // Only show prompt/completion split when available
                    if has_token_split {
                        div { class: "org-stat",
                            span { class: "org-stat-value",
                                {format_tokens(stats.total_prompt_tokens)}
                            }
                            span { class: "org-stat-label",
                                {t(l, "org.prompt_tokens")}
                            }
                        }
                        div { class: "org-stat",
                            span { class: "org-stat-value",
                                {format_tokens(stats.total_completion_tokens)}
                            }
                            span { class: "org-stat-label",
                                {t(l, "org.completion_tokens")}
                            }
                        }
                    }
                }

                // Per-model breakdown table
                if !stats.model_breakdown.is_empty() {
                    h3 { class: "org-section-title",
                        {t(l, "org.model_usage")}
                    }
                    div { class: "org-table-wrapper",
                        table { class: "org-table",
                            thead {
                                tr {
                                    th { {t(l, "org.model")} }
                                    th { {t(l, "org.tokens")} }
                                    th { {t(l, "org.spend")} }
                                }
                            }
                            tbody {
                                for model in &stats.model_breakdown {
                                    tr { key: "{model.model}",
                                        td { "{model.model}" }
                                        td {
                                            {format_tokens(model.total_tokens)}
                                        }
                                        td {
                                            {format!(
                                                "${:.2}", model.spend
                                            )}
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Compute the date range for the current billing month.
///
/// Returns `(start_date, end_date)` as `YYYY-MM-DD` strings where
/// start_date is the 1st of the current month and end_date is today.
///
/// On the web target this uses `js_sys::Date` to read the browser clock.
/// On the server target (SSR) it falls back to `chrono::Utc::now()`.
fn current_month_range() -> (String, String) {
    #[cfg(feature = "web")]
    {
        // js_sys::Date accesses the browser's local clock in WASM.
        let now = js_sys::Date::new_0();
        let year = now.get_full_year();
        // JS months are 0-indexed, so add 1 for calendar month
        let month = now.get_month() + 1;
        let day = now.get_date();
        let start = format!("{year:04}-{month:02}-01");
        let end = format!("{year:04}-{month:02}-{day:02}");
        (start, end)
    }
    #[cfg(not(feature = "web"))]
    {
        use chrono::Datelike;
        let today = chrono::Utc::now().date_naive();
        let start = format!("{:04}-{:02}-01", today.year(), today.month());
        let end = today.format("%Y-%m-%d").to_string();
        (start, end)
    }
}

/// Formats a token count into a human-readable string (e.g. "1.2M").
fn format_tokens(count: u64) -> String {
    const M: u64 = 1_000_000;
    const K: u64 = 1_000;

    if count >= M {
        format!("{:.1}M", count as f64 / M as f64)
    } else if count >= K {
        format!("{:.0}K", count as f64 / K as f64)
    } else {
        count.to_string()
    }
}

/// Returns mock organization members.
fn mock_members() -> Vec<OrgMember> {
    vec![
        OrgMember {
            id: "m1".into(),
            name: "Max Mustermann".into(),
            email: "max@example.com".into(),
            role: MemberRole::Admin,
            joined_at: "2026-01-10".into(),
        },
        OrgMember {
            id: "m2".into(),
            name: "Erika Musterfrau".into(),
            email: "erika@example.com".into(),
            role: MemberRole::Member,
            joined_at: "2026-01-15".into(),
        },
        OrgMember {
            id: "m3".into(),
            name: "Johann Schmidt".into(),
            email: "johann@example.com".into(),
            role: MemberRole::Member,
            joined_at: "2026-02-01".into(),
        },
        OrgMember {
            id: "m4".into(),
            name: "Anna Weber".into(),
            email: "anna@example.com".into(),
            role: MemberRole::Viewer,
            joined_at: "2026-02-10".into(),
        },
    ]
}

/// Returns mock billing usage data.
fn mock_usage() -> BillingUsage {
    BillingUsage {
        seats_used: 4,
        seats_total: 25,
        tokens_used: 847_000,
        tokens_limit: 1_000_000,
        billing_cycle_end: "2026-03-01".into(),
    }
}
