/**
 * Team Admin > Members
 * v0.3.4: custom team roles support
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function MembersSection({ teamId }) {
    const [members, setMembers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showAdd, setShowAdd] = useState(false);
    const [users, setUsers] = useState([]);
    const [roles, setRoles] = useState(['admin', 'member']);
    const [showRoles, setShowRoles] = useState(false);
    const [newRole, setNewRole] = useState('');

    const loadRoles = useCallback(async () => {
        try {
            const resp = await sw.api.get(`/api/v1/teams/${teamId}/roles`);
            setRoles(resp.data || ['admin', 'member']);
        } catch { setRoles(['admin', 'member']); }
    }, [teamId]);

    const load = useCallback(async () => {
        try {
            const data = await sw.api.teams.members(teamId);
            setMembers(data || []);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, [teamId]);

    useEffect(() => { load(); loadRoles(); }, [load, loadRoles]);

    async function openAdd() {
        setShowAdd(true);
        try {
            const resp = await sw.api.admin.users.list();
            setUsers(resp.data || []);
        } catch {
            // non-admin may not have access — leave empty
            setUsers([]);
        }
    }

    async function addMember(e) {
        e.preventDefault();
        const form = e.target;
        const userId = form.userId.value;
        const role = form.role.value;
        if (!userId) return;
        try {
            await sw.api.teams.addMember(teamId, userId, role);
            sw.toast('Member added', 'success');
            setShowAdd(false);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function updateRole(memberId, newRole) {
        try {
            await sw.api.teams.updateMember(teamId, memberId, newRole);
            sw.toast('Role updated', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function removeMember(memberId) {
        const ok = await sw.confirm('Remove this member from the team?', true);
        if (!ok) return;
        try {
            await sw.api.teams.removeMember(teamId, memberId);
            sw.toast('Member removed', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    if (loading) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    return html`
        <div>
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                <div style="flex:1"></div>
                <button class="btn-md btn-primary" onClick=${openAdd}>+ Add Member</button>
            </div>

            ${showAdd && html`
                <form class="admin-inline-form" style="margin-bottom:16px;" onSubmit=${addMember}>
                    <div class="form-row">
                        <div class="form-group"><label>User</label>
                            <select name="userId">
                                <option value="">Select\u2026</option>
                                ${users.map(u => html`<option key=${u.id} value=${u.id}>${u.username || u.email}</option>`)}
                            </select>
                        </div>
                        <div class="form-group"><label>Role</label>
                            <select name="role">
                                ${roles.map(r => html`<option key=${r} value=${r}>${r}</option>`)}
                            </select>
                        </div>
                    </div>
                    <div class="form-row" style="margin-top:8px;gap:8px;">
                        <button type="submit" class="btn-small btn-primary">Add</button>
                        <button type="button" class="btn-small" onClick=${() => setShowAdd(false)}>Cancel</button>
                    </div>
                </form>
            `}

            <div class="admin-list">
                ${members.length === 0 && html`<div class="empty-hint">No members</div>`}
                ${members.map(m => html`
                    <div class="admin-surface-row" key=${m.id || m.user_id}>
                        <strong style="flex:1;">${m.username || m.user_id}</strong>
                        <select value=${m.role || 'member'} style="width:100px;"
                                onChange=${e => updateRole(m.id || m.user_id, e.target.value)}>
                            ${roles.map(r => html`<option key=${r} value=${r}>${r}</option>`)}
                        </select>
                        <button class="btn-small btn-danger" onClick=${() => removeMember(m.id || m.user_id)}>Remove</button>
                    </div>
                `)}
            </div>

            <div style="margin-top:24px;border-top:1px solid var(--border-1);padding-top:12px;">
                <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                    <h4 style="margin:0;flex:1;">Team Roles</h4>
                    <button class="btn-small" onClick=${() => setShowRoles(!showRoles)}>
                        ${showRoles ? 'Hide' : 'Manage'}
                    </button>
                </div>
                <div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px;">
                    ${roles.map(r => html`<span key=${r} class="badge">${r}</span>`)}
                </div>
                ${showRoles && html`
                    <div style="display:flex;gap:8px;align-items:center;">
                        <input value=${newRole} onInput=${e => setNewRole(e.target.value)}
                               placeholder="New role name" style="width:150px;" />
                        <button class="btn-small btn-primary" onClick=${async () => {
                            if (!newRole.trim()) return;
                            const updated = [...new Set([...roles, newRole.trim()])];
                            try {
                                await sw.api.put('/api/v1/teams/' + teamId + '/roles', { roles: updated });
                                setRoles(updated);
                                setNewRole('');
                                sw.toast('Role added', 'success');
                            } catch (e) { sw.toast(e.message, 'error'); }
                        }}>Add Role</button>
                    </div>
                    <div class="admin-list" style="margin-top:8px;">
                        ${roles.filter(r => r !== 'admin' && r !== 'member').map(r => html`
                            <div class="admin-surface-row" key=${r}>
                                <span style="flex:1;">${r}</span>
                                <button class="btn-small btn-danger" onClick=${async () => {
                                    const updated = roles.filter(x => x !== r);
                                    try {
                                        await sw.api.put('/api/v1/teams/' + teamId + '/roles', { roles: updated });
                                        setRoles(updated);
                                        sw.toast('Role removed', 'success');
                                        load(); // re-check members
                                    } catch (e) { sw.toast(e.message, 'error'); }
                                }}>Remove</button>
                            </div>
                        `)}
                        ${roles.filter(r => r !== 'admin' && r !== 'member').length === 0 &&
                            html`<div class="empty-hint">No custom roles</div>`}
                    </div>
                `}
            </div>
        </div>
    `;
}
