import { useMemo } from 'react';
import { WeightSliderRow } from './weight-slider-row';
import { CollapsibleSection } from './collapsible-section';
import { TASK_TYPE_LABELS } from '@/lib/scoring';
import type { PriorityConfig } from '@/lib/scoring';

interface PriorityConfigPanelProps {
    config: PriorityConfig;
    onChange: (config: PriorityConfig) => void;
}

const TASK_TYPE_ORDER = ['missed_call', 'follow_up', 'campaign_lead', 'attempt_2', 'attempt_3'];

export const PriorityConfigPanel = ({ config, onChange }: PriorityConfigPanelProps) => {
    const updateTaskWeight = (taskType: string, weight: number) => {
        onChange({
            ...config,
            taskWeights: {
                ...config.taskWeights,
                [taskType]: { ...config.taskWeights[taskType], weight },
            },
        });
    };

    const updateTaskSla = (taskType: string, slaMinutes: number) => {
        onChange({
            ...config,
            taskWeights: {
                ...config.taskWeights,
                [taskType]: { ...config.taskWeights[taskType], slaMinutes },
            },
        });
    };

    const toggleTask = (taskType: string, enabled: boolean) => {
        onChange({
            ...config,
            taskWeights: {
                ...config.taskWeights,
                [taskType]: { ...config.taskWeights[taskType], enabled },
            },
        });
    };

    const badge = useMemo(() => {
        const entries = Object.values(config.taskWeights).filter(t => t.enabled);
        if (entries.length === 0) return 'All disabled';
        const avg = entries.reduce((s, t) => s + t.weight, 0) / entries.length;
        return `${entries.length} active · Avg ${avg.toFixed(1)}`;
    }, [config.taskWeights]);

    return (
        <CollapsibleSection
            title="Task Type Weights"
            subtitle="Higher weight = called first"
            badge={badge}
            defaultOpen
        >
            <div className="divide-y divide-tertiary">
                {TASK_TYPE_ORDER.map(taskType => {
                    const taskConfig = config.taskWeights[taskType];
                    if (!taskConfig) return null;
                    return (
                        <WeightSliderRow
                            key={taskType}
                            label={TASK_TYPE_LABELS[taskType] ?? taskType}
                            weight={taskConfig.weight}
                            onWeightChange={(w) => updateTaskWeight(taskType, w)}
                            enabled={taskConfig.enabled}
                            onToggle={(e) => toggleTask(taskType, e)}
                            slaMinutes={taskConfig.slaMinutes}
                            onSlaChange={(m) => updateTaskSla(taskType, m)}
                            showSla
                        />
                    );
                })}
            </div>
        </CollapsibleSection>
    );
};
