import { useState, useEffect, useCallback } from 'react';
import { API } from '@/api/API';
import { toast } from 'sonner';

export interface InterviewConfigItemOption {
    id?: string;
    optionLabel: string;
    optionValue: string;
    score: number;
    order: number;
}

export interface InterviewConfigItem {
    id?: string;
    itemKey: string;
    label: string;
    type: 'select' | 'text' | 'textarea' | 'number';
    order: number;
    isRequired: boolean;
    weight: number | null;
    maxScore: number | null;
    options?: InterviewConfigItemOption[];
}

export interface InterviewConfig {
    id?: string;
    configType: 'KT_MATRIX' | 'LEVEL2_FEEDBACK' | 'LEVEL3_FEEDBACK';
    name: string;
    version: string;
    isActive: boolean;
    items?: InterviewConfigItem[];
    createdAt?: string;
}

export function useInterviewConfigs() {
    const [ktMatrixConfig, setKtMatrixConfig] = useState<InterviewConfig | null>(null);
    const [level2Config, setLevel2Config] = useState<InterviewConfig | null>(null);
    const [level3Config, setLevel3Config] = useState<InterviewConfig | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const fetchConfig = useCallback(async (configType: string) => {
        try {
            const response: any = await API.getInterviewConfigByType(configType);
            if (response.data?.success) {
                return response.data.data as InterviewConfig;
            }
        } catch (err: any) {
            if (err?.response?.status !== 404) {
                console.warn(`Failed to fetch ${configType} config:`, err);
            }
        }
        return null;
    }, []);

    const loadAllConfigs = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const [kt, l2, l3] = await Promise.all([
                fetchConfig('KT_MATRIX'),
                fetchConfig('LEVEL2_FEEDBACK'),
                fetchConfig('LEVEL3_FEEDBACK')
            ]);
            setKtMatrixConfig(kt);
            setLevel2Config(l2);
            setLevel3Config(l3);
        } catch (err) {
            setError('Failed to load interview configurations');
            toast.error('Failed to load interview configurations');
        } finally {
            setLoading(false);
        }
    }, [fetchConfig]);

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

    return {
        ktMatrixConfig,
        level2Config,
        level3Config,
        loading,
        error,
        refresh: loadAllConfigs
    };
}
