/**
 * Workspace Selector Component
 * Dropdown to select workspace/shortcut from server
 */

import { useState, useEffect } from 'react';
import { fetchWorkspaces, WorkspaceItem } from '../shared/api-client';

interface WorkspaceSelectorProps {
    value: string;
    onChange: (workspaceId: string) => void;
}

export function WorkspaceSelector({ value, onChange }: WorkspaceSelectorProps) {
    const [workspaces, setWorkspaces] = useState<WorkspaceItem[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadWorkspaces();
    }, []);

    const loadWorkspaces = async () => {
        setLoading(true);
        try {
            const items = await fetchWorkspaces();
            setWorkspaces(items);

            // Restore last used workspace
            const stored = await chrome.storage.local.get(['lastWorkspace']);
            if (stored.lastWorkspace && !value) {
                onChange(stored.lastWorkspace);
            }
        } catch {
            // No workspaces available
        }
        setLoading(false);
    };

    const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const selected = e.target.value;
        onChange(selected);
        chrome.storage.local.set({ lastWorkspace: selected });
    };

    if (loading) {
        return (
            <div className="form-group">
                <label className="label">Workspace</label>
                <div style={{ fontSize: '11px', color: 'var(--muted-foreground)', padding: '8px 0' }}>
                    Loading...
                </div>
            </div>
        );
    }

    if (workspaces.length === 0) {
        return null; // Don't show if no workspaces
    }

    return (
        <div className="form-group">
            <label className="label">Workspace</label>
            <select className="select" value={value} onChange={handleChange}>
                <option value="">Default (no workspace)</option>
                {workspaces.map((ws) => (
                    <option key={ws.id} value={String(ws.id)}>
                        {ws.title}
                    </option>
                ))}
            </select>
        </div>
    );
}
