import { useState } from "preact/hooks";
import { useHordeState } from "../contexts/state";
import { formatNumber, formatTime } from "@common/utils";
import { calculateTotalKudosPerHour } from "../utils/calculations";
import styles from "../assets/stats-panel.module.css";

type ModelSortKey = 'name' | 'count' | 'queued' | 'jobs' | 'performance';
type SortDir = 'asc' | 'desc';

export const StatsPanel = () => {
    const { state } = useHordeState();
    const { user, workers, performance, models } = state;

    const [sortKey, setSortKey] = useState<ModelSortKey>('jobs');
    const [sortDir, setSortDir] = useState<SortDir>('desc');

    const ownWorkerIds = new Set(user?.worker_ids ?? []);
    const ownWorkers = workers.filter(w => ownWorkerIds.has(w.id));

    // Kudos/hour: sum of per-worker kudos/hour rates
    const kudosPerHour = calculateTotalKudosPerHour(ownWorkers);
    const totalUptime = ownWorkers.reduce((s, w) => s + w.uptime, 0);

    // Own model names set
    const ownModelNames = new Set(ownWorkers.flatMap(w => w.models));

    // Sort models
    const sortedModels = [...models].sort((a, b) => {
        let cmp = 0;
        if (sortKey === 'name') cmp = a.name.localeCompare(b.name);
        else if (sortKey === 'count') cmp = a.count - b.count;
        else if (sortKey === 'queued') cmp = a.queued - b.queued;
        else if (sortKey === 'jobs') cmp = a.jobs - b.jobs;
        else cmp = a.performance - b.performance;

        return sortDir === 'asc' ? cmp : -cmp;
    });

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

    const sortIndicator = (key: ModelSortKey) =>
        sortKey === key ? (sortDir === 'asc' ? ' ↑' : ' ↓') : '';

    return (
        <aside class={styles.panel}>
            <section class={styles.userStats}>
                {user && (<div class={styles.username}>{user.username}</div>)}
                <dl class={styles.stats}>
                    {user && <><div class={styles.stat}>
                        <dt>Kudos</dt>
                        <dd>{formatNumber(user.kudos)}</dd>
                    </div>
                        <div class={styles.stat}>
                            <dt>Kudos/h</dt>
                            <dd>{formatNumber(Math.round(kudosPerHour))}</dd>
                        </div>
                        <div class={styles.stat}>
                            <dt>Workers</dt>
                            <dd>{ownWorkers.length}/{user.worker_count}</dd>
                        </div>
                        <div class={styles.stat}>
                            <dt>Tokens generated</dt>
                            <dd>{formatNumber(user.records.contribution.tokens)}</dd>
                        </div>
                        <div class={styles.stat}>
                            <dt>Requests fulfilled</dt>
                            <dd>{formatNumber(user.records.fulfillment.text)}</dd>
                        </div>
                        <div class={styles.stat}>
                            <dt>Total uptime</dt>
                            <dd>{formatTime(totalUptime)}</dd>
                        </div>
                    </>}
                    <div class={styles.stat}>
                        <dt>Queued requests</dt>
                        <dd>{performance ? formatNumber(performance.queued_text_requests) : '—'}</dd>
                    </div>
                    <div class={styles.stat}>
                        <dt>Queued tokens</dt>
                        <dd>{performance ? formatNumber(performance.queued_tokens) : '—'}</dd>
                    </div>
                    <div class={styles.stat}>
                        <dt>Throughput (1m)</dt>
                        <dd>{performance ? `${formatNumber(performance.past_minute_tokens)} tok` : '—'}</dd>
                    </div>
                </dl>
            </section>

            <section class={styles.modelsSection}>
                <div class={styles.sectionTitle}>Models</div>
                <div class={styles.tableWrapper}>
                    <table class={styles.table}>
                        <thead>
                            <tr>
                                <th onClick={() => handleSort('name')}>Name{sortIndicator('name')}</th>
                                <th class={styles.colNum} onClick={() => handleSort('count')}>Workers{sortIndicator('count')}</th>
                                <th class={styles.colNum} onClick={() => handleSort('jobs')}>Jobs{sortIndicator('jobs')}</th>
                                <th class={styles.colNum} onClick={() => handleSort('queued')}>Queued{sortIndicator('queued')}</th>
                                <th class={styles.colNum} onClick={() => handleSort('performance')}>Perf{sortIndicator('performance')}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {sortedModels.map(m => (
                                <tr key={m.name} class={ownModelNames.has(m.name) ? styles.ownModel : undefined}>
                                    <td>{m.name}</td>
                                    <td class={styles.colNum}>{m.count}</td>
                                    <td class={styles.colNum}>{m.jobs}</td>
                                    <td class={styles.colNum}>{formatNumber(m.queued)}</td>
                                    <td class={styles.colNum}>{m.performance > 0 ? `${m.performance.toFixed(1)}` : '—'}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </section>
        </aside>
    );
};
