use crate::i18n::use_i18n;
use leptos::prelude::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;

#[cfg(not(target_arch = "wasm32"))]
fn spawn_local<F>(_fut: F)
where
    F: std::future::Future<Output = ()> + 'static,
{
    // On server side, don't execute async operations that require browser APIs
}
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Role {
    pub id: String,
    pub name: String,
    pub description: String,
    pub permissions: Vec<String>,
    pub created_at: String,
    pub updated_at: String,
    pub user_count: u32,
    pub is_system_role: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Permission {
    pub id: String,
    pub name: String,
    pub description: String,
    pub category: String,
    pub resource: String,
    pub action: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateRoleRequest {
    pub name: String,
    pub description: String,
    pub permissions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateRoleRequest {
    pub id: String,
    pub name: String,
    pub description: String,
    pub permissions: Vec<String>,
}

#[component]
pub fn AdminRoles() -> impl IntoView {
    let i18n = use_i18n();
    let (roles, set_roles) = signal(Vec::<Role>::new());
    let (permissions, set_permissions) = signal(Vec::<Permission>::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal(None::<String>);
    let (selected_role, set_selected_role) = signal(None::<Role>);
    let (show_create_modal, set_show_create_modal) = signal(false);
    let (show_edit_modal, set_show_edit_modal) = signal(false);
    let (show_permissions_modal, set_show_permissions_modal) = signal(false);
    let (search_term, set_search_term) = signal(String::new());

    // Fetch roles and permissions on mount
    Effect::new(move |_| {
        spawn_local(async move {
            match fetch_roles_and_permissions().await {
                Ok((roles_data, permissions_data)) => {
                    set_roles.set(roles_data);
                    set_permissions.set(permissions_data);
                    set_loading.set(false);
                }
                Err(e) => {
                    set_error.set(Some(e));
                    set_loading.set(false);
                }
            }
        });
    });

    // Filtered roles
    let filtered_roles = Memo::new(move |_| {
        let search = search_term.get().to_lowercase();
        roles
            .get()
            .into_iter()
            .filter(|role| {
                search.is_empty()
                    || role.name.to_lowercase().contains(&search)
                    || role.description.to_lowercase().contains(&search)
            })
            .collect::<Vec<_>>()
    });

    let delete_role = Action::new(move |role_id: &String| {
        let role_id = role_id.clone();
        async move {
            match delete_role_api(&role_id).await {
                Ok(_) => {
                    set_roles.update(|roles| roles.retain(|r| r.id != role_id));
                    Ok(())
                }
                Err(e) => {
                    set_error.set(Some(e.clone()));
                    Err(e)
                }
            }
        }
    });

    view! {
        <div class="min-h-screen bg-gray-50">
            <div class="py-6">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="pb-5 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <h1 class="text-3xl font-bold leading-tight text-gray-900">
                                "Role Management"
                            </h1>
                            <div class="flex space-x-3">
                                <button
                                    class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg"
                                    on:click=move |_| set_show_permissions_modal.set(true)
                                >
                                    {i18n.t("view-permissions")}
                                </button>
                                <button
                                    class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg"
                                    on:click=move |_| set_show_create_modal.set(true)
                                >
                                    {i18n.t("create-new-role")}
                                </button>
                            </div>
                        </div>
                    </div>

                    // Error Alert
                    <Show when=move || error.get().is_some()>
                        <div class="mt-4 bg-red-50 border border-red-200 rounded-md p-4">
                            <div class="flex">
                                <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                                </svg>
                                <div class="ml-3">
                                    <p class="text-sm text-red-800">
                                        {move || error.get().unwrap_or_default()}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </Show>

                    // Search
                    <div class="mt-6 bg-white shadow rounded-lg">
                        <div class="px-4 py-5 sm:p-6">
                            <div class="flex items-center justify-between">
                                <div class="flex-1 max-w-lg">
                                    <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("search-roles")}
                                    </label>
                                    <input
                                        type="text"
                                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                        placeholder="Search roles..."
                                        prop:value=move || search_term.get()
                                        on:input=move |ev| set_search_term.set(event_target_value(&ev))
                                    />
                                </div>
                                <div class="ml-4">
                                    <button
                                        class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg"
                                        on:click=move |_| set_search_term.set(String::new())
                                    >
                                        {i18n.t("clear")}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    // Roles Grid
                    <div class="mt-6">
                        <Show
                            when=move || !loading.get()
                            fallback=|| view! { <RolesGridSkeleton /> }
                        >
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                <For
                                    each=move || filtered_roles.get()
                                    key=|role| role.id.clone()
                                    children=move |role| {
                                        let role_name = role.name.clone();
                                        let role_description = role.description.clone();
                                        let role_id = role.id.clone();
                                        let role_is_system = role.is_system_role;
                                        let role_user_count = role.user_count;
                                        let role_permissions = role.permissions.clone();
                                        let role_permissions_len = role_permissions.len();
                                        let i18n = use_i18n();

                                        view! {
                                            <div class="bg-white overflow-hidden shadow rounded-lg">
                                                <div class="px-6 py-4">
                                                    <div class="flex items-center justify-between">
                                                        <div class="flex-1">
                                                            <h3 class="text-lg font-medium text-gray-900">
                                                                {role_name.clone()}
                                                            </h3>
                                                            <p class="text-sm text-gray-500 mt-1">
                                                                {role_description.clone()}
                                                            </p>
                                                        </div>
                                                        <div class="flex space-x-2">
                                                            <button
                                                                class="text-indigo-600 hover:text-indigo-900 text-sm font-medium"
                                                                on:click={
                                                                    let role_clone = role.clone();
                                                                    move |_| {
                                                                        set_selected_role.set(Some(role_clone.clone()));
                                                                        set_show_edit_modal.set(true);
                                                                    }
                                                                }
                                                            >
                                                                {i18n.t("edit")}
                                                            </button>
                                                            <Show when=move || !role_is_system>
                                                                <button
                                                                    class="text-red-600 hover:text-red-900 text-sm font-medium"
                                                                    on:click={
                                                                        let role_name_for_delete = role_name.clone();
                                                                        let role_id_for_delete = role_id.clone();
                                                                        move |_| {
                                                                            if let Some(window) = web_sys::window() {
                                                                                if window
                                                                                    .confirm_with_message(&format!("Are you sure you want to delete the role '{}'?", role_name_for_delete))
                                                                                    .unwrap_or(false)
                                                                                {
                                                                                    let _ = delete_role.dispatch(role_id_for_delete.clone());
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                >
                                                                    {i18n.t("delete")}
                                                                </button>
                                                            </Show>
                                                        </div>
                                                    </div>

                                                    <div class="mt-4">
                                                        <div class="flex items-center justify-between text-sm text-gray-500">
                                                            <span>{role_user_count} " users"</span>
                                                            <span>{role_permissions_len} " permissions"</span>
                                                        </div>

                                                        <div class="mt-3">
                                                            <div class="flex flex-wrap gap-1">
                                                                {role_permissions.iter().take(3).map(|perm| {
                                                                    view! {
                                                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                                                                            {perm.clone()}
                                                                        </span>
                                                                    }
                                                                }).collect::<Vec<_>>()}
                                                                <Show when={
                                                                    let len = role_permissions_len;
                                                                    move || len > 3
                                                                }>
                                                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                                                                        "+" {role_permissions_len - 3} " more"
                                                                    </span>
                                                                </Show>
                                                            </div>
                                                        </div>

                                                        <Show when=move || role.is_system_role>
                                                            <div class="mt-2">
                                                                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                                                    "System Role"
                                                                </span>
                                                            </div>
                                                        </Show>
                                                    </div>
                                                </div>
                                            </div>
                                        }
                                    }
                                />
                            </div>
                        </Show>
                    </div>
                </div>
            </div>

            // Create Role Modal
            <Show when=move || show_create_modal.get()>
                <CreateRoleModal
                    permissions=permissions.get()
                    on_close=move || set_show_create_modal.set(false)
                    on_role_created=move |role| {
                        set_roles.update(|roles| roles.push(role));
                        set_show_create_modal.set(false);
                    }
                />
            </Show>

            // Edit Role Modal
            <Show when=move || show_edit_modal.get()>
                <EditRoleModal
                    role=selected_role.get()
                    permissions=permissions.get()
                    on_close=move || set_show_edit_modal.set(false)
                    on_role_updated=move |updated_role| {
                        set_roles.update(|roles| {
                            if let Some(role) = roles.iter_mut().find(|r| r.id == updated_role.id) {
                                *role = updated_role;
                            }
                        });
                        set_show_edit_modal.set(false);
                    }
                />
            </Show>

            // Permissions Modal
            <Show when=move || show_permissions_modal.get()>
                <PermissionsModal
                    permissions=permissions.get()
                    on_close=move || set_show_permissions_modal.set(false)
                />
            </Show>
        </div>
    }
}

#[component]
fn RolesGridSkeleton() -> impl IntoView {
    view! {
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <For
                each=|| 0..6
                key=|i| *i
                children=move |_| {
                    view! {
                        <div class="bg-white overflow-hidden shadow rounded-lg animate-pulse">
                            <div class="px-6 py-4">
                                <div class="h-4 bg-gray-300 rounded w-3/4 mb-2"></div>
                                <div class="h-3 bg-gray-300 rounded w-1/2"></div>
                            </div>
                        </div>
                    }
                }
            />
        </div>
    }
}

#[component]
fn CreateRoleModal(
    permissions: Vec<Permission>,
    on_close: impl Fn() + 'static + Clone + Send + Sync,
    on_role_created: impl Fn(Role) + 'static + Clone + Send + Sync,
) -> impl IntoView {
    let i18n = use_i18n();
    let (form_data, set_form_data) = signal(CreateRoleRequest {
        name: String::new(),
        description: String::new(),
        permissions: Vec::new(),
    });
    let (submitting, set_submitting) = signal(false);
    let (error, set_error) = signal(None::<String>);

    // Group permissions by category
    let permissions_options = Memo::new(move |_prev: Option<&HashMap<String, Vec<Permission>>>| {
        let mut groups: HashMap<String, Vec<Permission>> = HashMap::new();
        for perm in permissions.iter() {
            let category = perm.category.clone();
            groups
                .entry(category)
                .or_insert_with(Vec::new)
                .push(perm.clone());
        }
        groups
    });

    let submit_form = Action::new({
        let on_role_created = on_role_created.clone();
        move |_: &()| {
            let form_data = form_data.get();
            let on_role_created = on_role_created.clone();
            async move {
                set_submitting.set(true);
                set_error.set(None);

                match create_role_api(form_data).await {
                    Ok(role) => {
                        on_role_created(role);
                        set_submitting.set(false);
                    }
                    Err(e) => {
                        set_error.set(Some(e));
                        set_submitting.set(false);
                    }
                }
            }
        }
    });

    // Create iterator functions outside view macro to avoid parsing issues
    let permission_groups_iter = move || permissions_options.get().into_iter().collect::<Vec<_>>();

    view! {
        <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">
                            {i18n.t("create-new-role")}
                        </h3>
                        <button
                            class="text-gray-400 hover:text-gray-600"
                            on:click={
                                let on_close_clone = on_close.clone();
                                move |_| on_close_clone()
                            }
                        >
                            <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>

                    <Show when=move || error.get().is_some()>
                        <div class="mb-4 bg-red-50 border border-red-200 rounded-md p-4">
                            <p class="text-sm text-red-800">
                                {move || error.get().unwrap_or_default()}
                            </p>
                        </div>
                    </Show>

                    <form on:submit=move |ev| {
                        ev.prevent_default();
                        submit_form.dispatch(());
                    }>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("role-name")}
                                </label>
                                <input
                                    type="text"
                                    required
                                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                    prop:value=move || form_data.get().name
                                    on:input=move |ev| {
                                        set_form_data.update(|data| data.name = event_target_value(&ev));
                                    }
                                />
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("description")}
                                </label>
                                <textarea
                                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                    rows="3"
                                    prop:value=move || form_data.get().description
                                    on:input=move |ev| {
                                        set_form_data.update(|data| data.description = event_target_value(&ev));
                                    }
                                ></textarea>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    {i18n.t("permissions")}
                                </label>
                                <div class="max-h-60 overflow-y-auto border border-gray-200 rounded-md p-3">
                                    <For
                                        each=permission_groups_iter
                                        key=|(category, _)| category.clone()
                                        children=move |(category, perms)| {
                                            view! {
                                                <div class="mb-4">
                                                    <h4 class="font-medium text-gray-900 mb-2">{category}</h4>
                                                    <div class="space-y-2">
                                                        <For
                                                            each=move || perms.clone()
                                                            key=|perm| perm.id.clone()
                                                            children=move |perm| {
                                                                let perm_id = perm.id.clone();
                                                                view! {
                                                                    <label class="flex items-center">
                                                                        <input
                                                                            type="checkbox"
                                                                            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                                                                            prop:checked=move || {
                                                                                let perm_id = perm_id.clone();
                                                                                form_data.get().permissions.contains(&perm_id)
                                                                            }
                                                                            on:change=move |ev| {
                                                                                let checked = event_target_checked(&ev);
                                                                                set_form_data.update(|data| {
                                                                                    if checked {
                                                                                        if !data.permissions.contains(&perm.id) {
                                                                                            data.permissions.push(perm.id.clone());
                                                                                        }
                                                                                    } else {
                                                                                        data.permissions.retain(|p| p != &perm.id);
                                                                                    }
                                                                                });
                                                                            }
                                                                        />
                                                                        <span class="ml-2 text-sm text-gray-700">
                                                                            {perm.name.clone()}
                                                                        </span>
                                                                    </label>
                                                                }
                                                            }
                                                        />
                                                    </div>
                                                </div>
                                            }
                                        }
                                    />
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end space-x-3 mt-6">
                            <button
                                type="button"
                                class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50"
                                on:click={
                                    let on_close_clone = on_close.clone();
                                    move |_| on_close_clone()
                                }
                            >
                                {i18n.t("cancel")}
                            </button>
                            <button
                                type="submit"
                                disabled=move || submitting.get()
                                class="bg-indigo-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                            >
                                <Show
                                    when=move || submitting.get()
                                    fallback=|| "Create Role"
                                >
                                    {i18n.t("creating")}
                                </Show>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }
}

#[component]
fn EditRoleModal(
    role: Option<Role>,
    permissions: Vec<Permission>,
    on_close: impl Fn() + 'static + Clone + Send + Sync,
    on_role_updated: impl Fn(Role) + 'static + Clone + Send + Sync,
) -> impl IntoView {
    let i18n = use_i18n();
    let role = role.unwrap_or_default();
    let (form_data, set_form_data) = signal(UpdateRoleRequest {
        id: role.id.clone(),
        name: role.name.clone(),
        description: role.description.clone(),
        permissions: role.permissions.clone(),
    });
    let (submitting, set_submitting) = signal(false);
    let (error, set_error) = signal(None::<String>);

    // Group permissions by category
    let permissions_options = Memo::new(move |_prev: Option<&HashMap<String, Vec<Permission>>>| {
        let mut groups: HashMap<String, Vec<Permission>> = HashMap::new();
        for perm in permissions.iter() {
            let category = perm.category.clone();
            groups
                .entry(category)
                .or_insert_with(Vec::new)
                .push(perm.clone());
        }
        groups
    });

    let submit_form = Action::new({
        let on_role_updated = on_role_updated.clone();
        move |_: &()| {
            let form_data = form_data.get();
            let on_role_updated = on_role_updated.clone();
            async move {
                set_submitting.set(true);
                set_error.set(None);

                match update_role_api(form_data).await {
                    Ok(role) => {
                        on_role_updated(role);
                        set_submitting.set(false);
                    }
                    Err(e) => {
                        set_error.set(Some(e));
                        set_submitting.set(false);
                    }
                }
            }
        }
    });

    // Create iterator functions outside view macro to avoid parsing issues
    let permission_groups_iter_edit =
        move || permissions_options.get().into_iter().collect::<Vec<_>>();

    view! {
        <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">
                            {i18n.t("edit-role")}
                        </h3>
                        <button
                            class="text-gray-400 hover:text-gray-600"
                            on:click={
                                let on_close_clone = on_close.clone();
                                move |_| on_close_clone()
                            }
                        >
                            <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>

                    <Show when=move || error.get().is_some()>
                        <div class="mb-4 bg-red-50 border border-red-200 rounded-md p-4">
                            <p class="text-sm text-red-800">
                                {move || error.get().unwrap_or_default()}
                            </p>
                        </div>
                    </Show>

                    <form on:submit=move |ev| {
                        ev.prevent_default();
                        let _ = submit_form.input();
                    }>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("role-name")}
                                </label>
                                <input
                                    type="text"
                                    required
                                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                    prop:value=move || form_data.get().name
                                    on:input=move |ev| {
                                        set_form_data.update(|data| data.name = event_target_value(&ev));
                                    }
                                />
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("description")}
                                </label>
                                <textarea
                                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                    rows="3"
                                    prop:value=move || form_data.get().description
                                    on:input=move |ev| {
                                        set_form_data.update(|data| data.description = event_target_value(&ev));
                                    }
                                ></textarea>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    {i18n.t("permissions")}
                                </label>
                                <div class="max-h-60 overflow-y-auto border border-gray-200 rounded-md p-3">
                                    <For
                                        each=permission_groups_iter_edit
                                        key=|(category, _)| category.clone()
                                        children=move |(category, perms)| {
                                            view! {
                                                <div class="mb-4">
                                                    <h4 class="font-medium text-gray-900 mb-2">{category}</h4>
                                                    <div class="space-y-2">
                                                        <For
                                                            each=move || perms.clone()
                                                            key=|perm| perm.id.clone()
                                                            children=move |perm| {
                                                                let perm_id_input = perm.id.clone();
                                                                view! {
                                                                    <label class="flex items-center">
                                                                        <input
                                                                            type="checkbox"
                                                                            class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                                                                            prop:checked=move || {
                                                                                let data = form_data.get();
                                                                                let perm_id = perm_id_input.clone();
                                                                                data.permissions.contains(&perm_id)
                                                                            }
                                                                            on:change=move |ev| {
                                                                                let checked = event_target_checked(&ev);
                                                                                set_form_data.update(|data| {
                                                                                    if checked {
                                                                                        if !data.permissions.contains(&perm.id) {
                                                                                            data.permissions.push(perm.id.clone());
                                                                                        }
                                                                                    } else {
                                                                                        data.permissions.retain(|p| p != &perm.id);
                                                                                    }
                                                                                });
                                                                            }
                                                                        />
                                                                        <span class="ml-2 text-sm text-gray-700">
                                                                            {perm.name.clone()}
                                                                        </span>
                                                                    </label>
                                                                }
                                                            }
                                                        />
                                                    </div>
                                                </div>
                                            }
                                        }
                                    />
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end space-x-3 mt-6">
                            <button
                                type="button"
                                class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50"
                                on:click={
                                    let on_close_clone = on_close.clone();
                                    move |_| on_close_clone()
                                }
                            >
                                {i18n.t("cancel")}
                            </button>
                            <button
                                type="submit"
                                disabled=move || submitting.get()
                                class="bg-indigo-600 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                            >
                                <Show
                                    when=move || submitting.get()
                                    fallback=|| "Update Role"
                                >
                                    {i18n.t("updating")}
                                </Show>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }
}

#[component]
fn PermissionsModal(
    permissions: Vec<Permission>,
    on_close: impl Fn() + 'static + Send + Sync + Clone,
) -> impl IntoView {
    let i18n = use_i18n();
    // Group permissions by category
    let permission_groups = Memo::new(move |_prev: Option<&HashMap<String, Vec<Permission>>>| {
        let mut groups: HashMap<String, Vec<Permission>> = HashMap::new();
        for perm in permissions.iter() {
            let category = perm.category.clone();
            groups
                .entry(category)
                .or_insert_with(Vec::new)
                .push(perm.clone());
        }
        groups
    });

    // Create iterator functions outside view macro to avoid parsing issues
    let permission_groups_iter_view =
        move || permission_groups.get().into_iter().collect::<Vec<_>>();

    view! {
        <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div class="relative top-10 mx-auto p-5 border w-full max-w-4xl shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">
                            {i18n.t("system-permissions")}
                        </h3>
                        <button
                            class="text-gray-400 hover:text-gray-600"
                            on:click={
                                let on_close_clone = on_close.clone();
                                move |_| on_close_clone()
                            }
                        >
                            <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>

                    <div class="max-h-96 overflow-y-auto">
                        <For
                            each=permission_groups_iter_view
                            key=|(category, _)| category.clone()
                            children=move |(category, perms)| {
                                view! {
                                    <div class="mb-6">
                                        <h4 class="font-medium text-gray-900 mb-3 text-lg border-b pb-2">
                                            {category}
                                        </h4>
                                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                            <For
                                                each=move || perms.clone()
                                                key=|perm| perm.id.clone()
                                                children=move |perm| {
                                                    view! {
                                                        <div class="bg-gray-50 p-3 rounded-lg">
                                                            <div class="font-medium text-sm text-gray-900">
                                                                {perm.name.clone()}
                                                            </div>
                                                            <div class="text-xs text-gray-500 mt-1">
                                                                {perm.description.clone()}
                                                            </div>
                                                            <div class="text-xs text-gray-400 mt-2">
                                                                {format!("{} : {}", perm.resource, perm.action)}
                                                            </div>
                                                        </div>
                                                    }
                                                }
                                            />
                                        </div>
                                    </div>
                                }
                            }
                        />
                    </div>
                </div>
            </div>
        </div>
    }
}

impl Default for Role {
    fn default() -> Self {
        Self {
            id: String::new(),
            name: String::new(),
            description: String::new(),
            permissions: Vec::new(),
            created_at: String::new(),
            updated_at: String::new(),
            user_count: 0,
            is_system_role: false,
        }
    }
}

impl Default for Permission {
    fn default() -> Self {
        Self {
            id: String::new(),
            name: String::new(),
            description: String::new(),
            category: String::new(),
            resource: String::new(),
            action: String::new(),
        }
    }
}

async fn fetch_roles_and_permissions() -> Result<(Vec<Role>, Vec<Permission>), String> {
    // Mock data for now - replace with actual API call
    let roles = vec![
        Role {
            id: "1".to_string(),
            name: "Administrator".to_string(),
            description: "Full system access".to_string(),
            permissions: vec!["1".to_string(), "2".to_string(), "3".to_string()],
            created_at: "2024-01-01T00:00:00Z".to_string(),
            updated_at: "2024-01-01T00:00:00Z".to_string(),
            user_count: 2,
            is_system_role: true,
        },
        Role {
            id: "2".to_string(),
            name: "User".to_string(),
            description: "Standard user access".to_string(),
            permissions: vec!["3".to_string()],
            created_at: "2024-01-01T00:00:00Z".to_string(),
            updated_at: "2024-01-01T00:00:00Z".to_string(),
            user_count: 10,
            is_system_role: true,
        },
        Role {
            id: "3".to_string(),
            name: "Moderator".to_string(),
            description: "Content moderation access".to_string(),
            permissions: vec!["3".to_string(), "4".to_string()],
            created_at: "2024-01-01T00:00:00Z".to_string(),
            updated_at: "2024-01-01T00:00:00Z".to_string(),
            user_count: 5,
            is_system_role: false,
        },
    ];

    let permissions = vec![
        Permission {
            id: "1".to_string(),
            name: "User Management".to_string(),
            description: "Create, read, update, and delete users".to_string(),
            category: "Administration".to_string(),
            resource: "users".to_string(),
            action: "manage".to_string(),
        },
        Permission {
            id: "2".to_string(),
            name: "Role Management".to_string(),
            description: "Create, read, update, and delete roles".to_string(),
            category: "Administration".to_string(),
            resource: "roles".to_string(),
            action: "manage".to_string(),
        },
        Permission {
            id: "3".to_string(),
            name: "Read Profile".to_string(),
            description: "View own profile information".to_string(),
            category: "Profile".to_string(),
            resource: "profile".to_string(),
            action: "read".to_string(),
        },
        Permission {
            id: "4".to_string(),
            name: "Content Moderation".to_string(),
            description: "Moderate user-generated content".to_string(),
            category: "Content".to_string(),
            resource: "content".to_string(),
            action: "moderate".to_string(),
        },
    ];

    Ok((roles, permissions))
}

async fn create_role_api(role_data: CreateRoleRequest) -> Result<Role, String> {
    // Mock implementation - replace with actual API call
    Ok(Role {
        id: format!("role_{}", 12345),
        name: role_data.name,
        description: role_data.description,
        permissions: role_data.permissions,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        updated_at: "2024-01-01T00:00:00Z".to_string(),
        user_count: 0,
        is_system_role: false,
    })
}

async fn update_role_api(role_data: UpdateRoleRequest) -> Result<Role, String> {
    // Mock implementation - replace with actual API call
    Ok(Role {
        id: role_data.id,
        name: role_data.name,
        description: role_data.description,
        permissions: role_data.permissions,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        updated_at: "2024-01-01T00:00:00Z".to_string(),
        user_count: 0,
        is_system_role: false,
    })
}

async fn delete_role_api(role_id: &str) -> Result<(), String> {
    // Mock implementation - replace with actual API call
    web_sys::console::log_1(&format!("Deleting role: {}", role_id).into());
    Ok(())
}
