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};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct User {
    pub id: String,
    pub email: String,
    pub name: String,
    pub roles: Vec<String>,
    pub status: UserStatus,
    pub created_at: String,
    pub last_login: Option<String>,
    pub is_verified: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum UserStatus {
    Active,
    Inactive,
    Suspended,
    Pending,
}

impl UserStatus {
    fn to_string(&self) -> String {
        // &'static str {
        let i18n = use_i18n();
        match self {
            UserStatus::Active => i18n.t("active"),
            UserStatus::Inactive => i18n.t("inactive"),
            UserStatus::Suspended => i18n.t("suspended"),
            UserStatus::Pending => i18n.t("pending"),
        }
    }

    fn badge_class(&self) -> &'static str {
        match self {
            UserStatus::Active => "bg-green-100 text-green-800",
            UserStatus::Inactive => "bg-gray-100 text-gray-800",
            UserStatus::Suspended => "bg-red-100 text-red-800",
            UserStatus::Pending => "bg-yellow-100 text-yellow-800",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserRequest {
    pub email: String,
    pub name: String,
    pub roles: Vec<String>,
    pub send_invitation: bool,
}

#[component]
pub fn AdminUsers() -> impl IntoView {
    let i18n = use_i18n();

    let (users, set_users) = signal(Vec::<User>::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal(None::<String>);
    let (selected_user, set_selected_user) = signal(None::<User>);
    let (show_create_modal, set_show_create_modal) = signal(false);
    let (show_edit_modal, set_show_edit_modal) = signal(false);
    let (search_term, set_search_term) = signal(String::new());
    let (status_filter, set_status_filter) = signal(String::new());

    // Fetch users on mount
    Effect::new(move |_| {
        spawn_local(async move {
            match fetch_users().await {
                Ok(data) => {
                    set_users.set(data);
                    set_loading.set(false);
                }
                Err(e) => {
                    set_error.set(Some(e));
                    set_loading.set(false);
                }
            }
        });
    });

    // Filtered users
    let filtered_users = Memo::new(move |_| {
        let search = search_term.get().to_lowercase();
        let status = status_filter.get();

        users
            .get()
            .into_iter()
            .filter(|user| {
                let matches_search = search.is_empty()
                    || user.name.to_lowercase().contains(&search)
                    || user.email.to_lowercase().contains(&search);

                let matches_status = status.is_empty()
                    || user.status.to_string().to_lowercase() == status.to_lowercase();

                matches_search && matches_status
            })
            .collect::<Vec<_>>()
    });

    let delete_user = Action::new(move |user_id: &String| {
        let user_id = user_id.clone();
        async move {
            match delete_user_api(&user_id).await {
                Ok(_) => {
                    set_users.update(|users| users.retain(|u| u.id != user_id));
                    Ok(())
                }
                Err(e) => {
                    set_error.set(Some(e.clone()));
                    Err(e)
                }
            }
        }
    });

    let toggle_user_status = Action::new(move |user_id: &String| {
        let user_id = user_id.clone();
        async move {
            match toggle_user_status_api(&user_id).await {
                Ok(updated_user) => {
                    set_users.update(|users| {
                        if let Some(user) = users.iter_mut().find(|u| u.id == user_id) {
                            *user = updated_user;
                        }
                    });
                    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">
                                {i18n.t("user-management")}
                            </h1>
                            <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("add-new-user")}
                            </button>
                        </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 and Filter
                    <div class="mt-6 bg-white shadow rounded-lg">
                        <div class="px-4 py-5 sm:p-6">
                            <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">
                                       {i18n.t("search-users")}
                                    </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 by name or email..."
                                        prop:value=move || search_term.get()
                                        on:input=move |ev| set_search_term.set(event_target_value(&ev))
                                    />
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">
                                        {i18n.t("filter-by-status")}
                                    </label>
                                    <select
                                        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 || status_filter.get()
                                        on:change=move |ev| set_status_filter.set(event_target_value(&ev))
                                    >
                                        <option value="">{i18n.t("all-status")}</option>
                                        <option value="active">{i18n.t("active")}</option>
                                        <option value="inactive">{i18n.t("inactive")}</option>
                                        <option value="suspended">{i18n.t("suspended")}</option>
                                        <option value="pending">{i18n.t("pending")}</option>
                                    </select>
                                </div>
                                <div class="flex items-end">
                                    <button
                                        class="w-full 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());
                                            set_status_filter.set(String::new());
                                        }
                                    >
                                        {i18n.t("clear-filters")}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    // Users Table
                    <div class="mt-6 bg-white shadow overflow-hidden sm:rounded-md">
                        <Show
                            when=move || !loading.get()
                            fallback=|| view! { <UsersTableSkeleton /> }
                        >
                            <div class="min-w-full overflow-hidden overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200">
                                    <thead class="bg-gray-50">
                                        <tr>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {i18n.t("user")}
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {i18n.t("roles")}
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {i18n.t("status")}
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {i18n.t("last-login")}
                                            </th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                {i18n.t("actions")}
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-gray-200">
                                        <For
                                            each=move || filtered_users.get()
                                            key=|user| user.id.clone()
                                            children=move |user| {
                                                let delete_id = user.id.clone();
                                                let activate_id = user.id.clone();
                                                let user_name = user.name.clone();
                                                let user_status = user.status.clone();
                                                view! {
                                                    <tr>
                                                        <td class="px-6 py-4 whitespace-nowrap">
                                                            <div class="flex items-center">
                                                                <div class="flex-shrink-0 h-10 w-10">
                                                                    <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                                                        <span class="text-sm font-medium text-gray-700">
                                                                            {user.name.chars().next().unwrap_or('U')}
                                                                        </span>
                                                                    </div>
                                                                </div>
                                                                <div class="ml-4">
                                                                    <div class="text-sm font-medium text-gray-900">
                                                                        {user.name.clone()}
                                                                    </div>
                                                                    <div class="text-sm text-gray-500">
                                                                        {user.email.clone()}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td class="px-6 py-4 whitespace-nowrap">
                                                            <div class="flex flex-wrap gap-1">
                                                                {user.roles.iter().map(|role| {
                                                                    view! {
                                                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                                                            {role.clone()}
                                                                        </span>
                                                                    }
                                                                }).collect::<Vec<_>>()}
                                                            </div>
                                                        </td>
                                                        <td class="px-6 py-4 whitespace-nowrap">
                                                            <span class=format!("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {}", user.status.badge_class())>
                                                                {user.status.to_string()}
                                                            </span>
                                                        </td>
                                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                            {user.last_login.as_ref().unwrap_or(&"Never".to_string()).clone()}
                                                        </td>
                                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                            <div class="flex space-x-2">
                                                                <button
                                                                    class="text-indigo-600 hover:text-indigo-900"
                                                                    on:click=move |_| {
                                                                        set_selected_user.set(Some(user.clone()));
                                                                        set_show_edit_modal.set(true);
                                                                    }
                                                                >
                                                                    "Edit"
                                                                </button>
                                                                <button
                                                                    class="text-yellow-600 hover:text-yellow-900"
                                                                    on:click=move |_| { toggle_user_status.dispatch(activate_id.clone()); }
                                                                >
                                                                    {match user_status {
                                                                        UserStatus::Active => "Suspend",
                                                                        _ => "Activate",
                                                                    }}
                                                                </button>
                                                                <button
                                                                    class="text-red-600 hover:text-red-900"
                                                                    on:click=move |_| {
                                                                        if let Some(window) = web_sys::window() {
                                                                            if window.confirm_with_message(&format!("Are you sure you want to delete user {}?", user_name)).unwrap_or(false) {
                                                                                let _ = delete_user.dispatch(delete_id.clone());
                                                                            }
                                                                        }
                                                                    }
                                                                >
                                                                    "Delete"
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                }
                                            }
                                        />
                                    </tbody>
                                </table>
                            </div>
                        </Show>
                    </div>
                </div>
            </div>

            // Create User Modal
            <Show when=move || show_create_modal.get()>
                <CreateUserModal
                    on_close=move || set_show_create_modal.set(false)
                    on_user_created=move |user| {
                        set_users.update(|users| users.push(user));
                        set_show_create_modal.set(false);
                    }
                />
            </Show>

            // Edit User Modal
            <Show when=move || show_edit_modal.get()>
                <EditUserModal
                    user=selected_user.get()
                    on_close=move || set_show_edit_modal.set(false)
                    on_user_updated=move |updated_user| {
                        set_users.update(|users| {
                            if let Some(user) = users.iter_mut().find(|u| u.id == updated_user.id) {
                                *user = updated_user;
                            }
                        });
                        set_show_edit_modal.set(false);
                    }
                />
            </Show>
        </div>
    }
}

#[component]
fn UsersTableSkeleton() -> impl IntoView {
    view! {
        <div class="animate-pulse">
            <div class="bg-gray-50 px-6 py-3">
                <div class="h-4 bg-gray-200 rounded w-full"></div>
            </div>
            <div class="divide-y divide-gray-200">
                {(0..5).map(|_| view! {
                    <div class="px-6 py-4">
                        <div class="flex items-center space-x-4">
                            <div class="h-10 w-10 bg-gray-200 rounded-full"></div>
                            <div class="flex-1 space-y-2">
                                <div class="h-4 bg-gray-200 rounded w-1/4"></div>
                                <div class="h-4 bg-gray-200 rounded w-1/3"></div>
                            </div>
                        </div>
                    </div>
                }).collect::<Vec<_>>()}
            </div>
        </div>
    }
}

#[component]
fn CreateUserModal(
    on_close: impl Fn() + 'static + Clone,
    on_user_created: impl Fn(User) + 'static + Clone + Send + Sync,
) -> impl IntoView {
    let i18n = use_i18n();
    let (form_data, set_form_data) = signal(CreateUserRequest {
        email: String::new(),
        name: String::new(),
        roles: Vec::new(),
        send_invitation: true,
    });
    let (submitting, set_submitting) = signal(false);
    let (error, set_error) = signal(None::<String>);

    let available_roles = vec![
        "admin".to_string(),
        "user".to_string(),
        "moderator".to_string(),
    ];

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

            match create_user_api(form_data).await {
                Ok(user) => {
                    on_user_created(user);
                    set_submitting.set(false);
                }
                Err(e) => {
                    set_error.set(Some(e));
                    set_submitting.set(false);
                }
            }
        }
    });

    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-md 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">
                            "Create New User"
                        </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("email")}
                                </label>
                                <input
                                    type="email"
                                    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().email
                                    on:input=move |ev| {
                                        let value = event_target_value(&ev);
                                        set_form_data.update(|data| data.email = value);
                                    }
                                />
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("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| {
                                        let value = event_target_value(&ev);
                                        set_form_data.update(|data| data.name = value);
                                    }
                                />
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("roles")}
                                </label>
                                <div class="mt-2 space-y-2">
                                    <For
                                        each=move || available_roles.clone()
                                        key=|role| role.clone()
                                        children=move |role| {
                                            let role_for_memo = role.clone();
                                            let role_checked = Memo::new(move |_| {
                                                form_data.get().roles.contains(&role_for_memo)
                                            });

                                            view! {
                                                <div class="flex items-center">
                                                    <input
                                                        type="checkbox"
                                                        class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                                                        prop:checked=move || role_checked.get()
                                                        on:change={
                                                            let role_clone = role.clone();
                                                            move |ev| {
                                                                let checked = event_target_checked(&ev);
                                                                let role_for_update = role_clone.clone();
                                                                set_form_data.update(|data| {
                                                                    if checked {
                                                                        if !data.roles.contains(&role_for_update) {
                                                                            data.roles.push(role_for_update);
                                                                        }
                                                                    } else {
                                                                        data.roles.retain(|r| r != &role_for_update);
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    />
                                                    <label class="ml-2 text-sm text-gray-900">
                                                        {role.clone()}
                                                    </label>
                                                </div>
                                            }
                                        }
                                    />
                                </div>
                            </div>

                            <div class="flex items-center">
                                <input
                                    type="checkbox"
                                    class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                                    prop:checked=move || form_data.get().send_invitation
                                    on:change=move |ev| {
                                        let checked = event_target_checked(&ev);
                                        set_form_data.update(|data| data.send_invitation = checked);
                                    }
                                />
                                <label class="ml-2 text-sm text-gray-900">
                                    {i18n.t("send-invitation-email")}
                                </label>
                            </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 User"
                                >
                                    {i18n.t("creating")}
                                </Show>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }
}

#[component]
fn EditUserModal(
    user: Option<User>,
    on_close: impl Fn() + Send + Sync + Clone + 'static,
    on_user_updated: impl Fn(User) + Send + Sync + Clone + 'static,
) -> impl IntoView {
    let i18n = use_i18n();
    let user = user.unwrap_or_default();
    let (form_data, set_form_data) = signal(UpdateUserRequest {
        id: user.id.clone(),
        email: user.email.clone(),
        name: user.name.clone(),
        roles: user.roles.clone(),
    });
    let (submitting, set_submitting) = signal(false);
    let (error, set_error) = signal(None::<String>);

    let available_roles = vec![
        "admin".to_string(),
        "user".to_string(),
        "moderator".to_string(),
    ];

    let submit_form = Action::new({
        let form_data = form_data.clone();
        let set_submitting = set_submitting.clone();
        let set_error = set_error.clone();
        let on_user_updated = on_user_updated.clone();

        move |_: &()| {
            let form_data = form_data.get();
            let on_user_updated = on_user_updated.clone();

            async move {
                set_submitting.set(true);
                set_error.set(None);

                match update_user_api(form_data).await {
                    Ok(user) => {
                        on_user_updated(user);
                        set_submitting.set(false);
                    }
                    Err(e) => {
                        set_error.set(Some(e));
                        set_submitting.set(false);
                    }
                }
            }
        }
    });

    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-md 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-user")}
                        </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("email")}
                                </label>
                                <input
                                    type="email"
                                    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().email
                                    on:input=move |ev| {
                                        let value = event_target_value(&ev);
                                        set_form_data.update(|data| data.email = value);
                                    }
                                />
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                  {i18n.t("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| {
                                        let value = event_target_value(&ev);
                                        set_form_data.update(|data| data.name = value);
                                    }
                                />
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    {i18n.t("roles")}
                                </label>
                                <div class="mt-2 space-y-2">
                                    <For
                                        each=move || available_roles.clone()
                                        key=|role| role.clone()
                                        children=move |role| {
                                            let role_clone = role.clone();
                                            let role_checked = Memo::new(move |_| {
                                                form_data.get().roles.contains(&role_clone)
                                            });

                                            view! {
                                                <div class="flex items-center">
                                                    <input
                                                        type="checkbox"
                                                        class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                                                        prop:checked=move || role_checked.get()
                                                        on:change={
                                                            let role_clone2 = role.clone();
                                                            move |ev| {
                                                                let checked = event_target_checked(&ev);
                                                                let role_for_update = role_clone2.clone();
                                                                let role_for_retain = role_clone2.clone();
                                                                set_form_data.update(|data| {
                                                                    if checked {
                                                                        if !data.roles.contains(&role_for_update) {
                                                                            data.roles.push(role_for_update);
                                                                        }
                                                                    } else {
                                                                        data.roles.retain(|r| r != &role_for_retain);
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    />
                                                    <label class="ml-2 text-sm text-gray-900">
                                                        {role.clone()}
                                                    </label>
                                                </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 User"
                                >
                                    {i18n.t("updating")}
                                </Show>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    }
}

impl Default for User {
    fn default() -> Self {
        Self {
            id: String::new(),
            email: String::new(),
            name: String::new(),
            roles: vec!["user".to_string()],
            status: UserStatus::Active,
            created_at: String::new(),
            last_login: None,
            is_verified: false,
        }
    }
}

// API Functions
async fn fetch_users() -> Result<Vec<User>, String> {
    // Mock data for now - replace with actual API call
    Ok(vec![
        User {
            id: "1".to_string(),
            email: "admin@example.com".to_string(),
            name: "Admin User".to_string(),
            roles: vec!["admin".to_string(), "user".to_string()],
            status: UserStatus::Active,
            created_at: "2024-01-01T00:00:00Z".to_string(),
            last_login: Some("2024-01-15T10:30:00Z".to_string()),
            is_verified: true,
        },
        User {
            id: "2".to_string(),
            email: "user@example.com".to_string(),
            name: "Regular User".to_string(),
            roles: vec!["user".to_string()],
            status: UserStatus::Active,
            created_at: "2024-01-02T00:00:00Z".to_string(),
            last_login: Some("2024-01-14T15:45:00Z".to_string()),
            is_verified: true,
        },
    ])
}

async fn create_user_api(user_data: CreateUserRequest) -> Result<User, String> {
    // Mock implementation - replace with actual API call
    Ok(User {
        id: format!("user_{}", 12345),
        email: user_data.email,
        name: user_data.name,
        roles: user_data.roles,
        status: UserStatus::Active,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        last_login: None,
        is_verified: false,
    })
}

async fn update_user_api(user_data: UpdateUserRequest) -> Result<User, String> {
    // Mock implementation - replace with actual API call
    Ok(User {
        id: user_data.id,
        email: user_data.email,
        name: user_data.name,
        roles: user_data.roles,
        status: UserStatus::Active,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        last_login: None,
        is_verified: true,
    })
}

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

async fn toggle_user_status_api(user_id: &str) -> Result<User, String> {
    // Mock implementation - replace with actual API call
    Ok(User {
        id: user_id.to_string(),
        email: "updated@example.com".to_string(),
        name: "Updated User".to_string(),
        roles: vec!["user".to_string()],
        status: UserStatus::Active,
        created_at: "2024-01-01T00:00:00Z".to_string(),
        last_login: Some("2024-01-01T10:00:00Z".to_string()),
        is_verified: true,
    })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateUserRequest {
    pub id: String,
    pub email: String,
    pub name: String,
    pub roles: Vec<String>,
}
