import React, { useState, useEffect, useCallback } from 'react';
import { API } from '@/api/API';
import { toast } from 'sonner';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Trash2, Plus, Save, Loader2, RotateCcw, Edit3, ChevronUp, ChevronDown } from 'lucide-react';

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

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

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

const CONFIG_TYPES = [
    { value: 'KT_MATRIX', label: 'KT Matrix (Level 1)', description: 'Scored criteria for Level 1 interview assessment' },
    { value: 'LEVEL2_FEEDBACK', label: 'Level 2 Feedback', description: 'Qualitative feedback fields for Level 2 interview' },
    { value: 'LEVEL3_FEEDBACK', label: 'Level 3 Feedback', description: 'Qualitative feedback fields for Level 3 interview' },
];

const InterviewConfigManagement: React.FC = () => {
    const [configs, setConfigs] = useState<InterviewConfig[]>([]);
    const [, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('KT_MATRIX');
    const [showEditor, setShowEditor] = useState(false);
    const [editingConfig, setEditingConfig] = useState<InterviewConfig | null>(null);
    const [saving, setSaving] = useState(false);
    const [initializing, setInitializing] = useState(false);

    const fetchConfigs = useCallback(async () => {
        try {
            setLoading(true);
            const response: any = await API.getInterviewConfigs();
            if (response.data?.success) {
                setConfigs(response.data.data || []);
            }
        } catch (error) {
            console.error('Fetch configs error:', error);
            toast.error('Failed to load interview configurations');
        } finally {
            setLoading(false);
        }
    }, []);

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

    const getActiveConfig = (type: string) => configs.find(c => c.configType === type && c.isActive);

    const handleCreateNew = (configType: string) => {
        const defaults: Record<string, ConfigItem[]> = {
            KT_MATRIX: [
                { itemKey: 'example_criterion', label: 'Example Criterion', type: 'select', order: 1, isRequired: true, weight: 5, maxScore: 10, options: [
                    { optionLabel: 'Excellent', optionValue: 'excellent', score: 10, order: 1 },
                    { optionLabel: 'Good', optionValue: 'good', score: 5, order: 2 }
                ]}
            ],
            LEVEL2_FEEDBACK: [
                { itemKey: 'strategicVision', label: 'Strategic Vision', type: 'textarea', order: 1, isRequired: true, weight: null, maxScore: null },
                { itemKey: 'managementCapabilities', label: 'Management Capabilities', type: 'textarea', order: 2, isRequired: true, weight: null, maxScore: null },
                { itemKey: 'additionalComments', label: 'Additional Comments', type: 'textarea', order: 3, isRequired: false, weight: null, maxScore: null }
            ],
            LEVEL3_FEEDBACK: [
                { itemKey: 'businessVision', label: 'Business Vision & Strategy', type: 'textarea', order: 1, isRequired: true, weight: null, maxScore: null },
                { itemKey: 'leadership', label: 'Leadership & Decision Making', type: 'textarea', order: 2, isRequired: true, weight: null, maxScore: null },
                { itemKey: 'additionalComments', label: 'Additional Comments', type: 'textarea', order: 3, isRequired: false, weight: null, maxScore: null }
            ]
        };

        setEditingConfig({
            configType: configType as any,
            name: `${CONFIG_TYPES.find(t => t.value === configType)?.label || 'New Config'}`,
            version: `v${new Date().toISOString().split('T')[0]}`,
            isActive: true,
            items: defaults[configType] || []
        });
        setShowEditor(true);
    };

    const handleEdit = async (configId: string) => {
        try {
            setLoading(true);
            const response: any = await API.getInterviewConfigById(configId);
            if (response.data?.success) {
                setEditingConfig(response.data.data);
                setShowEditor(true);
            }
        } catch (error) {
            toast.error('Failed to load configuration for editing');
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async () => {
        if (!editingConfig) return;
        if (!editingConfig.name || !editingConfig.version) {
            toast.error('Name and version are required');
            return;
        }
        if (!editingConfig.items || editingConfig.items.length === 0) {
            toast.error('Add at least one item');
            return;
        }
        // Validate KT Matrix total weight
        if (editingConfig.configType === 'KT_MATRIX') {
            const totalWeight = editingConfig.items.reduce((sum, i) => sum + (Number(i.weight) || 0), 0);
            if (Math.abs(totalWeight - 100) > 0.01) {
                toast.error(`KT Matrix total weight must be 100. Current: ${totalWeight}`);
                return;
            }
            for (const item of editingConfig.items) {
                if (item.type === 'select' && (!item.options || item.options.length === 0)) {
                    toast.error(`Select item "${item.label}" must have options`);
                    return;
                }
            }
        }

        try {
            setSaving(true);
            const payload = {
                configType: editingConfig.configType,
                name: editingConfig.name,
                version: editingConfig.version,
                items: editingConfig.items.map((item, idx) => ({
                    ...item,
                    order: item.order || idx + 1,
                    options: item.options?.map((opt, oIdx) => ({ ...opt, order: opt.order || oIdx + 1 }))
                }))
            };

            if (editingConfig.id) {
                await API.updateInterviewConfig(editingConfig.id, payload);
                toast.success('Configuration updated successfully');
            } else {
                await API.createInterviewConfig(payload);
                toast.success('New configuration published successfully');
            }
            setShowEditor(false);
            setEditingConfig(null);
            await fetchConfigs();
        } catch (error: any) {
            console.error('Save error:', error);
            toast.error(error?.response?.data?.message || 'Failed to save configuration');
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (configId: string) => {
        if (!confirm('Are you sure you want to delete this configuration?')) return;
        try {
            await API.deleteInterviewConfig(configId);
            toast.success('Configuration deleted');
            await fetchConfigs();
        } catch (error) {
            toast.error('Failed to delete configuration');
        }
    };

    const handleInitializeDefaults = async () => {
        if (!confirm('This will reset all interview configurations to system defaults. Continue?')) return;
        try {
            setInitializing(true);
            await API.initializeDefaultInterviewConfigs();
            toast.success('Default configurations initialized');
            await fetchConfigs();
        } catch (error) {
            toast.error('Failed to initialize defaults');
        } finally {
            setInitializing(false);
        }
    };

    const addItem = () => {
        if (!editingConfig) return;
        const newItem: ConfigItem = {
            itemKey: `field_${(editingConfig.items?.length || 0) + 1}`,
            label: '',
            type: editingConfig.configType === 'KT_MATRIX' ? 'select' : 'textarea',
            order: (editingConfig.items?.length || 0) + 1,
            isRequired: true,
            weight: editingConfig.configType === 'KT_MATRIX' ? 5 : null,
            maxScore: editingConfig.configType === 'KT_MATRIX' ? 10 : null,
            options: editingConfig.configType === 'KT_MATRIX' ? [
                { optionLabel: 'Option 1', optionValue: 'opt1', score: 10, order: 1 },
                { optionLabel: 'Option 2', optionValue: 'opt2', score: 5, order: 2 }
            ] : undefined
        };
        setEditingConfig({ ...editingConfig, items: [...(editingConfig.items || []), newItem] });
    };

    const removeItem = (index: number) => {
        if (!editingConfig) return;
        const newItems = editingConfig.items?.filter((_, i) => i !== index) || [];
        // Re-order
        const reOrdered = newItems.map((item, i) => ({ ...item, order: i + 1 }));
        setEditingConfig({ ...editingConfig, items: reOrdered });
    };

    const updateItem = (index: number, field: keyof ConfigItem, value: any) => {
        if (!editingConfig) return;
        const newItems = [...(editingConfig.items || [])];
        newItems[index] = { ...newItems[index], [field]: value };
        setEditingConfig({ ...editingConfig, items: newItems });
    };

    const addOption = (itemIndex: number) => {
        if (!editingConfig) return;
        const newItems = [...(editingConfig.items || [])];
        const item = newItems[itemIndex];
        if (!item.options) item.options = [];
        item.options.push({ optionLabel: '', optionValue: '', score: 0, order: item.options.length + 1 });
        setEditingConfig({ ...editingConfig, items: newItems });
    };

    const updateOption = (itemIndex: number, optionIndex: number, field: keyof ConfigOption, value: any) => {
        if (!editingConfig) return;
        const newItems = [...(editingConfig.items || [])];
        if (newItems[itemIndex].options) {
            newItems[itemIndex].options![optionIndex] = { ...newItems[itemIndex].options![optionIndex], [field]: value };
            setEditingConfig({ ...editingConfig, items: newItems });
        }
    };

    const removeOption = (itemIndex: number, optionIndex: number) => {
        if (!editingConfig) return;
        const newItems = [...(editingConfig.items || [])];
        if (newItems[itemIndex].options) {
            newItems[itemIndex].options = newItems[itemIndex].options!.filter((_, i) => i !== optionIndex);
            setEditingConfig({ ...editingConfig, items: newItems });
        }
    };

    const totalWeight = editingConfig?.configType === 'KT_MATRIX'
        ? (editingConfig.items || []).reduce((sum, i) => sum + (Number(i.weight) || 0), 0)
        : 0;

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-2xl font-bold text-slate-900">Interview Configuration</h2>
                    <p className="text-slate-500 text-sm mt-1">Manage KT Matrix criteria and feedback fields for all interview levels</p>
                </div>
                <Button variant="outline" onClick={handleInitializeDefaults} disabled={initializing} className="gap-2">
                    <RotateCcw size={16} /> {initializing ? 'Initializing...' : 'Reset to Defaults'}
                </Button>
            </div>

            <Tabs value={activeTab} onValueChange={setActiveTab}>
                <TabsList className="grid w-full grid-cols-3">
                    {CONFIG_TYPES.map(t => (
                        <TabsTrigger key={t.value} value={t.value}>{t.label}</TabsTrigger>
                    ))}
                </TabsList>
                {CONFIG_TYPES.map(type => {
                    const activeConfig = getActiveConfig(type.value);
                    const typeConfigs = configs.filter(c => c.configType === type.value);
                    return (
                        <TabsContent key={type.value} value={type.value}>
                            <Card>
                                <CardHeader className="flex flex-row items-center justify-between">
                                    <div>
                                        <CardTitle className="text-lg">{type.label}</CardTitle>
                                        <p className="text-sm text-slate-500">{type.description}</p>
                                    </div>
                                    <Button onClick={() => handleCreateNew(type.value)} className="gap-2">
                                        <Plus size={16} /> Publish New Version
                                    </Button>
                                </CardHeader>
                                <CardContent>
                                    {activeConfig ? (
                                        <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg">
                                            <div className="flex items-center justify-between">
                                                <div>
                                                    <p className="font-semibold text-green-800">Active: {activeConfig.name}</p>
                                                    <p className="text-sm text-green-700">Version {activeConfig.version} • {activeConfig.items?.length || 0} items</p>
                                                </div>
                                                <div className="flex gap-2">
                                                    <Button variant="ghost" size="sm" onClick={() => activeConfig.id && handleEdit(activeConfig.id)}>
                                                        <Edit3 size={16} />
                                                    </Button>
                                                </div>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-800">
                                            No active configuration found. Click "Publish New Version" to create one, or "Reset to Defaults" to initialize system defaults.
                                        </div>
                                    )}

                                    <h3 className="text-sm font-semibold text-slate-700 mb-3">Version History</h3>
                                    {typeConfigs.length === 0 ? (
                                        <p className="text-sm text-slate-500">No versions found.</p>
                                    ) : (
                                        <div className="space-y-2">
                                            {typeConfigs.map(cfg => (
                                                <div key={cfg.id} className={`flex items-center justify-between p-3 rounded-lg border ${cfg.isActive ? 'bg-green-50 border-green-200' : 'bg-white border-slate-200'}`}>
                                                    <div className="flex items-center gap-3">
                                                        {cfg.isActive && <Badge className="bg-green-600">Active</Badge>}
                                                        <span className="font-medium text-sm">{cfg.name}</span>
                                                        <span className="text-xs text-slate-500">{cfg.version}</span>
                                                        <span className="text-xs text-slate-400">{cfg.items?.length || 0} items</span>
                                                    </div>
                                                    <div className="flex items-center gap-1">
                                                        <Button variant="ghost" size="sm" onClick={() => cfg.id && handleEdit(cfg.id)}>
                                                            <Edit3 size={14} />
                                                        </Button>
                                                        <Button variant="ghost" size="sm" className="text-re-red hover:text-re-red-hover" onClick={() => cfg.id && handleDelete(cfg.id)}>
                                                            <Trash2 size={14} />
                                                        </Button>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        </TabsContent>
                    );
                })}
            </Tabs>            {/* Precision Engineered Editor Dialog */}
            <Dialog open={showEditor} onOpenChange={setShowEditor}>
                <DialogContent className="max-w-[95vw] w-full lg:max-w-7xl p-0 overflow-hidden border-none shadow-2xl rounded-2xl flex flex-col max-h-[95vh]">
                    {/* Compact Minimalist Header */}
                    <div className="px-5 py-4 border-b border-slate-100 bg-white flex shrink-0 items-center justify-between">
                        <div className="flex items-center gap-4">
                            <div>
                                <DialogTitle className="text-lg font-bold text-slate-900 leading-none">
                                    {editingConfig?.id ? 'Edit Configuration' : 'New Configuration'}
                                </DialogTitle>
                                <DialogDescription className="text-[11px] text-slate-500 mt-1 uppercase tracking-wider font-semibold">
                                    {editingConfig?.configType.replace(/_/g, ' ')} · {editingConfig?.version || 'v1.0'}
                                </DialogDescription>
                            </div>
                            {editingConfig?.configType === 'KT_MATRIX' && (
                                <div className={`px-3 py-1.5 rounded-md text-[10px] font-black uppercase tracking-tight ${totalWeight === 100 ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-red-50 text-re-red-hover border border-red-100'}`}>
                                    Weight: {totalWeight}% / 100%
                                </div>
                            )}
                        </div>
                        <div className="flex items-center gap-2">
                        </div>
                    </div>

                    <div className="flex-1 overflow-y-auto px-6 py-4 bg-white space-y-6 custom-scrollbar">
                        {editingConfig && (
                            <div className="space-y-6">
                                {/* Compact Meta Row */}
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end bg-slate-50/40 p-4 rounded-xl border border-slate-100">
                                    <div className="space-y-1.5">
                                        <Label className="text-[10px] font-bold text-slate-400 uppercase tracking-widest pl-1">Name</Label>
                                        <Input 
                                            value={editingConfig.name} 
                                            onChange={e => setEditingConfig({ ...editingConfig, name: e.target.value })} 
                                            className="h-9 border-slate-200 bg-white shadow-none text-sm font-normal" 
                                        />
                                    </div>
                                    <div className="space-y-1.5">
                                        <Label className="text-[10px] font-bold text-slate-400 uppercase tracking-widest pl-1">Version</Label>
                                        <Input 
                                            value={editingConfig.version} 
                                            onChange={e => setEditingConfig({ ...editingConfig, version: e.target.value })} 
                                            className="h-9 border-slate-200 bg-white shadow-none text-sm font-normal"
                                        />
                                    </div>
                                    <div className="flex items-center justify-end h-9">
                                        <Button variant="outline" onClick={addItem} className="h-full border-dashed border-slate-300 text-slate-500 hover:text-slate-900 text-xs font-bold px-4">
                                            <Plus size={14} className="mr-2" /> Add Criteria
                                        </Button>
                                    </div>
                                </div>

                                {/* Items Area with Horizontal Guard */}
                                <div className="overflow-x-auto custom-scrollbar-x-slim pb-4 -mx-1 px-1">
                                    <div className="min-w-[900px] border border-slate-100 rounded-xl">
                                        <table className="w-full text-left border-collapse table-fixed">
                                            <thead>
                                                <tr className="bg-slate-50/50 border-b border-slate-100 text-[10px] uppercase font-black text-slate-400 tracking-[0.1em]">
                                                    <th className="px-4 py-2 w-12 text-center">#</th>
                                                    <th className="px-4 py-2 w-[35%]">Label</th>
                                                    <th className="px-4 py-2 w-[20%]">Data Key</th>
                                                    <th className="px-4 py-2 w-32">Type</th>
                                                    {editingConfig.configType === 'KT_MATRIX' && (
                                                        <>
                                                            <th className="px-4 py-2 w-24">Weight</th>
                                                            <th className="px-4 py-2 w-20">Max</th>
                                                        </>
                                                    )}
                                                    <th className="px-4 py-2 w-16 text-center">Req.</th>
                                                    <th className="px-4 py-2 w-10"></th>
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-slate-50">
                                                {(editingConfig.items || []).map((item, index) => (
                                                    <React.Fragment key={index}>
                                                        <tr className="group hover:bg-slate-50/10 transition-colors">
                                                            <td className="px-4 py-3 text-slate-300 font-bold text-[11px] align-top pt-5 text-center">{String(index + 1).padStart(2, '0')}</td>
                                                            <td className="px-4 py-3 align-top">
                                                                <Input 
                                                                    value={item.label} 
                                                                    onChange={e => updateItem(index, 'label', e.target.value)} 
                                                                    className="h-10 border-slate-100 hover:border-slate-300 focus:bg-white bg-slate-50/30 text-sm font-normal transition-all" 
                                                                    placeholder="Age/Qualification etc."
                                                                />
                                                            </td>
                                                            <td className="px-4 py-3 align-top">
                                                                <Input 
                                                                    value={item.itemKey} 
                                                                    onChange={e => updateItem(index, 'itemKey', e.target.value)} 
                                                                    className="h-10 border-slate-100 hover:border-slate-300 focus:bg-white bg-slate-50/30 font-mono text-[11px] text-slate-500" 
                                                                />
                                                            </td>
                                                            <td className="px-4 py-3 align-top">
                                                                <Select value={item.type} onValueChange={(v: any) => updateItem(index, 'type', v)}>
                                                                    <SelectTrigger className="h-10 border-slate-100 hover:border-slate-300 bg-slate-50/30 text-xs focus:ring-0">
                                                                        <SelectValue />
                                                                    </SelectTrigger>
                                                                    <SelectContent>
                                                                        <SelectItem value="select">Options</SelectItem>
                                                                        <SelectItem value="text">One Liner</SelectItem>
                                                                        <SelectItem value="textarea">Paragraph</SelectItem>
                                                                        <SelectItem value="number">Numeric</SelectItem>
                                                                    </SelectContent>
                                                                </Select>
                                                            </td>
                                                            {editingConfig.configType === 'KT_MATRIX' && (
                                                                <>
                                                            <td className="px-4 py-3 align-top">
                                                                <div className="relative group/num">
                                                                    <Input 
                                                                        type="number" 
                                                                        value={item.weight || ''} 
                                                                        onChange={e => updateItem(index, 'weight', parseFloat(e.target.value) || 0)} 
                                                                        className="h-10 w-full border-slate-100 bg-slate-50/30 text-sm font-normal text-right pr-8 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                                                                    />
                                                                    <div className="absolute right-0.5 top-0.5 bottom-0.5 flex flex-col border-l border-slate-200/50 bg-white/40 rounded-r-md overflow-hidden opacity-40 group-hover/num:opacity-100 transition-opacity">
                                                                        <button 
                                                                            type="button"
                                                                            onClick={() => updateItem(index, 'weight', (item.weight || 0) + 1)}
                                                                            className="flex-1 px-1.5 hover:bg-slate-200/50 flex items-center justify-center border-b border-slate-200/50"
                                                                        >
                                                                            <ChevronUp size={10} className="text-slate-600" />
                                                                        </button>
                                                                        <button 
                                                                            type="button"
                                                                            onClick={() => updateItem(index, 'weight', Math.max(0, (item.weight || 0) - 1))}
                                                                            className="flex-1 px-1.5 hover:bg-slate-200/50 flex items-center justify-center"
                                                                        >
                                                                            <ChevronDown size={10} className="text-slate-600" />
                                                                        </button>
                                                                    </div>
                                                                    <span className="absolute left-2 top-1/2 -translate-y-1/2 text-[9px] text-slate-300 font-bold">%</span>
                                                                </div>
                                                            </td>
                                                            <td className="px-4 py-3 align-top">
                                                                <div className="relative group/num">
                                                                    <Input 
                                                                        type="number" 
                                                                        value={item.maxScore || ''} 
                                                                        onChange={e => updateItem(index, 'maxScore', parseFloat(e.target.value) || 0)} 
                                                                        className="h-10 border-slate-100 bg-slate-50/30 text-sm font-normal text-right pr-6 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                                                                    />
                                                                    <div className="absolute right-0.5 top-0.5 bottom-0.5 flex flex-col border-l border-slate-200/50 bg-white/40 rounded-r-md overflow-hidden opacity-40 group-hover/num:opacity-100 transition-opacity">
                                                                        <button 
                                                                            type="button"
                                                                            onClick={() => updateItem(index, 'maxScore', (item.maxScore || 0) + 1)}
                                                                            className="flex-1 px-1.5 hover:bg-slate-200/50 flex items-center justify-center border-b border-slate-200/50"
                                                                        >
                                                                            <ChevronUp size={10} className="text-slate-600" />
                                                                        </button>
                                                                        <button 
                                                                            type="button"
                                                                            onClick={() => updateItem(index, 'maxScore', Math.max(0, (item.maxScore || 0) - 1))}
                                                                            className="flex-1 px-1.5 hover:bg-slate-200/50 flex items-center justify-center"
                                                                        >
                                                                            <ChevronDown size={10} className="text-slate-600" />
                                                                        </button>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                                </>
                                                            )}
                                                            <td className="px-4 py-3 align-top text-center pt-5">
                                                                <input 
                                                                    type="checkbox" 
                                                                    checked={item.isRequired} 
                                                                    onChange={e => updateItem(index, 'isRequired', e.target.checked)} 
                                                                    className="w-4 h-4 accent-slate-900 border-slate-300"
                                                                />
                                                            </td>
                                                            <td className="px-4 py-3 align-top pt-4">
                                                                <Button variant="ghost" size="icon" className="h-8 w-8 text-slate-200 hover:text-red-500 hover:bg-red-50" onClick={() => removeItem(index)}>
                                                                    <Trash2 size={16} />
                                                                </Button>
                                                            </td>
                                                        </tr>
                                                        
                                                        {item.type === 'select' && (
                                                            <tr className="bg-slate-50/30">
                                                                <td colSpan={1}></td>
                                                                <td colSpan={editingConfig.configType === 'KT_MATRIX' ? 7 : 5} className="px-4 py-4">
                                                                    <div className="flex flex-col gap-3">
                                                                        <div className="flex items-center justify-between border-b border-slate-200/50 pb-2 mb-2">
                                                                            <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-2">
                                                                                <div className="w-1 h-3 bg-red-400 rounded-full" /> Options
                                                                            </p>
                                                                            <Button variant="ghost" size="sm" className="h-7 px-3 text-[10px] font-bold uppercase text-slate-600 hover:bg-white border border-transparent hover:border-slate-200" onClick={() => addOption(index)}>
                                                                                <Plus className="w-3 h-3 mr-1.5" /> Append Option
                                                                            </Button>
                                                                        </div>
                                                                        <div className="grid grid-cols-12 gap-3 mb-2 px-1">
                                                                             <div className="col-span-6 text-[9px] font-black uppercase text-slate-300 tracking-tighter">Display Label</div>
                                                                             <div className="col-span-3 text-[9px] font-black uppercase text-slate-300 tracking-tighter">API Value</div>
                                                                             <div className="col-span-2 text-[9px] font-black uppercase text-slate-300 tracking-tighter">Score</div>
                                                                        </div>
                                                                        <div className="space-y-2">
                                                                            {(item.options || []).map((opt, optIndex) => (
                                                                                <div key={optIndex} className="grid grid-cols-12 gap-3 items-center group/opt">
                                                                                    <div className="col-span-6">
                                                                                        <Input placeholder="Label" value={opt.optionLabel} onChange={e => updateOption(index, optIndex, 'optionLabel', e.target.value)} className="h-9 border-slate-200 bg-white text-xs font-normal" />
                                                                                    </div>
                                                                                    <div className="col-span-3">
                                                                                        <Input placeholder="Value" value={opt.optionValue} onChange={e => updateOption(index, optIndex, 'optionValue', e.target.value)} className="h-9 border-slate-200 bg-white text-xs font-mono" />
                                                                                    </div>
                                                                                    <div className="col-span-2">
                                                                                        <div className="relative group/optnum">
                                                                                            <Input 
                                                                                                type="number" 
                                                                                                placeholder="0" 
                                                                                                value={opt.score} 
                                                                                                onChange={e => updateOption(index, optIndex, 'score', parseFloat(e.target.value) || 0)} 
                                                                                                className="h-9 border-slate-200 bg-white text-xs font-normal text-right pr-6 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" 
                                                                                            />
                                                                                            <div className="absolute right-0.5 top-0.5 bottom-0.5 flex flex-col border-l border-slate-100 bg-slate-50/50 rounded-r-md overflow-hidden opacity-0 group-hover/optnum:opacity-100 transition-opacity">
                                                                                                <button onClick={() => updateOption(index, optIndex, 'score', (opt.score || 0) + 1)} className="flex-1 px-1 hover:bg-slate-200 flex items-center justify-center border-b border-slate-100">
                                                                                                    <ChevronUp size={8} />
                                                                                                </button>
                                                                                                <button onClick={() => updateOption(index, optIndex, 'score', (opt.score || 0) - 1)} className="flex-1 px-1 hover:bg-slate-200 flex items-center justify-center">
                                                                                                    <ChevronDown size={8} />
                                                                                                </button>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                    <div className="col-span-1 flex justify-center">
                                                                                        <Button variant="ghost" size="icon" className="h-8 w-8 text-slate-300 hover:text-red-500 opacity-0 group-hover/opt:opacity-100" onClick={() => removeOption(index, optIndex)}>
                                                                                            <Trash2 size={13} />
                                                                                        </Button>
                                                                                    </div>
                                                                                </div>
                                                                            ))}
                                                                        </div>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        )}
                                                    </React.Fragment>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>

                    <div className="px-6 py-4 bg-slate-50 border-t border-slate-100 flex shrink-0 justify-end gap-3">
                        <Button variant="ghost" className="px-6 h-10 text-xs font-bold text-slate-500 hover:bg-slate-200 transition-colors" onClick={() => setShowEditor(false)}>
                            Dismiss
                        </Button>
                        <Button 
                            className="bg-slate-900 hover:bg-slate-950 text-white px-8 h-10 rounded-lg text-xs font-black uppercase tracking-widest shadow-xl shadow-slate-200 transition-all active:scale-95"
                            onClick={handleSave}
                            disabled={saving}
                        >
                            {saving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
                            Commit Changes
                        </Button>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
};

export default InterviewConfigManagement;
