import { useState } from "preact/hooks";
import { useHordeState } from "../contexts/state";
import { WorkerCard } from "./worker-card";
import type { WorkerData } from "../utils/api";
import styles from "../assets/workers-panel.module.css";

type WorkerSortKey = 'name' | 'uptime' | 'requests' | 'kudos' | 'context' | 'length';
type SortDir = 'asc' | 'desc';

const SORT_LABELS: Record<WorkerSortKey, string> = {
    name: 'Name',
    uptime: 'Uptime',
    requests: 'Requests',
    kudos: 'Kudos',
    context: 'Max Context',
    length: 'Max Length',
};

const sortWorkers = (workers: WorkerData[], key: WorkerSortKey, dir: SortDir): WorkerData[] => {
    return [...workers].sort((a, b) => {
        let cmp = 0;
        switch (key) {
            case 'name':     cmp = a.name.localeCompare(b.name); break;
            case 'uptime':   cmp = a.uptime - b.uptime; break;
            case 'requests': cmp = a.requests_fulfilled - b.requests_fulfilled; break;
            case 'kudos':    cmp = a.kudos_rewards - b.kudos_rewards; break;
            case 'context':  cmp = a.max_context_length - b.max_context_length; break;
            case 'length':   cmp = a.max_length - b.max_length; break;
        }
        return dir === 'asc' ? cmp : -cmp;
    });
};

export const WorkersPanel = () => {
    const { state } = useHordeState();
    const { workers, user } = state;

    const [sortKey, setSortKey] = useState<WorkerSortKey>('name');
    const [sortDir, setSortDir] = useState<SortDir>('asc');

    const ownWorkerIds = new Set(user?.worker_ids ?? []);
    const sorted = sortWorkers(workers, sortKey, sortDir);

    const handleSort = (key: WorkerSortKey) => {
        if (key === sortKey) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
        else { setSortKey(key); setSortDir('desc'); }
    };

    return (
        <section class={styles.panel}>
            <div class={styles.header}>
                <span class={styles.count}>{workers.length} workers</span>
                <div class={styles.sortBar}>
                    {(Object.keys(SORT_LABELS) as WorkerSortKey[]).map(key => (
                        <button
                            key={key}
                            class={sortKey === key ? styles.sortActive : undefined}
                            onClick={() => handleSort(key)}
                        >
                            {SORT_LABELS[key]}
                            {sortKey === key ? (sortDir === 'asc' ? ' ↑' : ' ↓') : ''}
                        </button>
                    ))}
                </div>
            </div>
            <div class={styles.list}>
                {sorted.map(w => (
                    <WorkerCard key={w.id} worker={w} isOwn={ownWorkerIds.has(w.id)} />
                ))}
            </div>
        </section>
    );
};
