<script>
    let { user = null, roles = [], adminPath = 'loom', status = null, errors = [] } = $props();

    let name = $state('');
    let email = $state('');
    let password = $state('');
    let passwordConfirmation = $state('');
    let selectedRoles = $state([]);
    let allRoles = $state([]);

    $effect(() => {
        allRoles = roles;
        if (user) {
            name = user.name || '';
            email = user.email || '';
            selectedRoles = user.roles ? user.roles.map(r => r.id) : [];
        }
    });

    function toggleRole(roleId) {
        if (selectedRoles.includes(roleId)) {
            selectedRoles = selectedRoles.filter(id => id !== roleId);
        } else {
            selectedRoles = [...selectedRoles, roleId];
        }
    }
</script>

<div class="ui container">
    <div class="ui grid">
        <div class="sixteen wide column">
            <h1 class="ui header">
                <i class="user icon"></i>
                <div class="content">
                    {user ? 'Edit User' : 'Create New User'}
                    <div class="sub header">{user ? `Editing: ${user.name}` : 'Fill in the details below to create a new system user'}</div>
                </div>
            </h1>
        </div>

        <div class="sixteen wide column">
            {#if status}
                <div class="ui positive message">
                    <i class="close icon"></i>
                    <p>{status}</p>
                </div>
            {/if}

            {#if errors && errors.length > 0}
                <div class="ui negative message">
                    <i class="close icon"></i>
                    <ul class="list">
                        {#each errors as error}
                            <li>{error}</li>
                        {/each}
                    </ul>
                </div>
            {/if}

            <form class="ui form" method="POST" action="{window.location.origin.endsWith('/') ? window.location.origin : window.location.origin + '/'}{adminPath.startsWith('/') ? adminPath.substring(1) : adminPath}/users{user ? '/' + user.id : ''}">
                <input type="hidden" name="_token" value={document.querySelector('meta[name="csrf-token"]').getAttribute('content')}>
                {#if user}
                    <input type="hidden" name="_method" value="PUT">
                {/if}

                <div class="ui segment">
                    <div class="field required">
                        <label for="user-name">Full Name</label>
                        <input type="text" id="user-name" name="name" bind:value={name} placeholder="John Doe" required>
                    </div>

                    <div class="field required">
                        <label for="user-email">Email Address</label>
                        <input type="email" id="user-email" name="email" bind:value={email} placeholder="john@example.com" required disabled={user?.is_protected}>
                    </div>

                    <div class="field">
                        <label for="user-roles">Roles</label>
                        <div id="user-roles" class="ui segment basic" style="padding: 0;">
                            <div class="ui grid">
                                {#each roles as role}
                                    <div class="four wide column">
                                        <div class="ui checkbox">
                                            <input
                                                type="checkbox"
                                                name="roles[]"
                                                value={role.id}
                                                id="role-{role.id}"
                                                checked={selectedRoles.includes(role.id)}
                                                onchange={() => toggleRole(role.id)}
                                            >
                                            <label for="role-{role.id}">{role.name}</label>
                                        </div>
                                    </div>
                                {/each}
                            </div>
                        </div>
                    </div>

                    <div class="two fields">
                        <div class="field {user ? '' : 'required'}">
                            <label for="user-password">Password {user ? '(Leave blank to keep current)' : ''}</label>
                            <input type="password" id="user-password" name="password" bind:value={password} placeholder="••••••••" required={!user}>
                        </div>
                        <div class="field {user ? '' : 'required'}">
                            <label for="user-password-confirm">Confirm Password</label>
                            <input type="password" id="user-password-confirm" name="password_confirmation" bind:value={passwordConfirmation} placeholder="••••••••" required={!user}>
                        </div>
                    </div>
                </div>

                <button class="ui primary button" type="submit">
                    <i class="save icon"></i> {user ? 'Update User' : 'Create User'}
                </button>
                <a href="{window.location.origin.endsWith('/') ? window.location.origin : window.location.origin + '/'}{adminPath.startsWith('/') ? adminPath.substring(1) : adminPath}/users" class="ui button">Cancel</a>
            </form>
        </div>
    </div>
</div>
