import React from 'react';

const DEPT_COLORS = {
    HR: { color: '#3b82f6', bg: 'rgba(59,130,246,0.08)', label: '🧑‍💼 HR / Personal' },
    IT: { color: '#10b981', bg: 'rgba(16,185,129,0.08)', label: '💻 IT' },
    VG: { color: '#f59e0b', bg: 'rgba(245,158,11,0.08)', label: '👔 Vorgesetzter' },
    BK: { color: '#a78bfa', bg: 'rgba(167,139,250,0.08)', label: '💶 Buchhaltung / Lohn' },
};

const TAG_STYLES = {
    critical:  { background: 'rgba(239,68,68,0.15)',   color: '#ef4444' },
    important: { background: 'rgba(245,158,11,0.15)',  color: '#f59e0b' },
    normal:    { background: 'rgba(100,116,139,0.12)', color: '#64748b' },
};

const ChecklistEditor = ({ items, checkedItems, onChange, disabled = false }) => {
    const handleToggle = (key) => {
        if (disabled) return;
        onChange({ ...checkedItems, [key]: !checkedItems[key] });
    };

    // Check if items have phase/dept structure
    const isGrouped = items.length > 0 && items[0].phase !== undefined;

    if (!isGrouped) {
        // Legacy flat list
        return (
            <div className="checklist-editor">
                {items.map((item) => (
                    <div key={item.key} className="checklist-item">
                        <label className="checklist-label">
                            <input
                                type="checkbox"
                                className="checklist-checkbox"
                                checked={!!checkedItems[item.key]}
                                onChange={() => handleToggle(item.key)}
                                disabled={disabled}
                            />
                            <span className="checklist-text">{item.label}</span>
                        </label>
                    </div>
                ))}
            </div>
        );
    }

    // Grouped by phase → department
    const phases = [...new Set(items.map(i => i.phase))];
    const totalItems = items.length;
    const totalChecked = items.filter(i => !!checkedItems[i.key]).length;
    const totalPct = totalItems > 0 ? Math.round((totalChecked / totalItems) * 100) : 0;

    return (
        <div>
            {/* Overall progress */}
            <div style={{ marginBottom: '16px', padding: '12px 16px', background: 'var(--bg-secondary)', borderRadius: '8px', border: '1px solid var(--border-color)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                    <span style={{ fontSize: '12px', fontWeight: 700, color: 'var(--text-secondary)' }}>Gesamtfortschritt</span>
                    <span style={{ fontSize: '12px', fontFamily: 'monospace', color: totalPct === 100 ? '#10b981' : 'var(--text-muted)' }}>
                        {totalChecked} / {totalItems} · {totalPct}%
                    </span>
                </div>
                <div style={{ height: '4px', background: 'var(--border-color)', borderRadius: '2px', overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${totalPct}%`, background: totalPct === 100 ? '#10b981' : 'var(--cereda-primary)', borderRadius: '2px', transition: 'width 0.3s' }} />
                </div>
            </div>

            {phases.map(phase => {
                const phaseItems = items.filter(i => i.phase === phase);
                const phaseChecked = phaseItems.filter(i => !!checkedItems[i.key]).length;
                const phasePct = Math.round((phaseChecked / phaseItems.length) * 100);
                const depts = [...new Set(phaseItems.map(i => i.dept))];

                return (
                    <div key={phase} style={{ marginBottom: '16px', border: '1px solid var(--border-color)', borderRadius: '10px', overflow: 'hidden' }}>
                        {/* Phase header */}
                        <div style={{ padding: '10px 16px', background: 'var(--bg-tertiary)', borderBottom: '1px solid var(--border-color)', display: 'flex', alignItems: 'center', gap: '12px' }}>
                            <span style={{ fontSize: '12px', fontWeight: 700, color: 'var(--text-primary)', flex: 1 }}>{phase}</span>
                            <span style={{ fontSize: '11px', fontFamily: 'monospace', color: phasePct === 100 ? '#10b981' : 'var(--text-muted)' }}>
                                {phaseChecked}/{phaseItems.length}
                            </span>
                            <div style={{ width: '60px', height: '3px', background: 'var(--border-color)', borderRadius: '2px', overflow: 'hidden' }}>
                                <div style={{ height: '100%', width: `${phasePct}%`, background: phasePct === 100 ? '#10b981' : 'var(--cereda-primary)', transition: 'width 0.3s' }} />
                            </div>
                        </div>

                        {/* Department columns */}
                        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${depts.length}, 1fr)`, gap: '1px', background: 'var(--border-color)' }}>
                            {depts.map(dept => {
                                const dc = DEPT_COLORS[dept] || { color: 'var(--text-muted)', bg: 'var(--bg-secondary)', label: dept };
                                const deptItems = phaseItems.filter(i => i.dept === dept);

                                return (
                                    <div key={dept} style={{ background: 'var(--bg-card)', padding: '10px 12px' }}>
                                        <div style={{ fontSize: '10px', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: dc.color, borderLeft: `3px solid ${dc.color}`, paddingLeft: '6px', marginBottom: '8px' }}>
                                            {dc.label}
                                        </div>
                                        {deptItems.map(item => {
                                            const checked = !!checkedItems[item.key];
                                            const tagStyle = TAG_STYLES[item.tag] || TAG_STYLES.normal;
                                            return (
                                                <div
                                                    key={item.key}
                                                    onClick={() => handleToggle(item.key)}
                                                    style={{
                                                        padding: '7px 8px',
                                                        marginBottom: '5px',
                                                        borderRadius: '6px',
                                                        border: `1px solid ${checked ? dc.color + '50' : 'var(--border-color)'}`,
                                                        borderLeft: `3px solid ${dc.color}`,
                                                        background: checked ? dc.bg : 'var(--bg-secondary)',
                                                        cursor: disabled ? 'default' : 'pointer',
                                                        transition: 'all 0.15s',
                                                        opacity: checked ? 0.7 : 1,
                                                    }}
                                                >
                                                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: '7px' }}>
                                                        <div style={{
                                                            width: '15px', height: '15px', flexShrink: 0, marginTop: '1px',
                                                            border: `1.5px solid ${checked ? dc.color : 'var(--border-color)'}`,
                                                            borderRadius: '3px', background: checked ? dc.color : 'transparent',
                                                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                                                            fontSize: '9px', color: '#fff',
                                                        }}>
                                                            {checked ? '✓' : ''}
                                                        </div>
                                                        <div style={{ flex: 1 }}>
                                                            <div style={{ fontSize: '11.5px', fontWeight: 600, color: checked ? 'var(--text-muted)' : 'var(--text-primary)', textDecoration: checked ? 'line-through' : 'none', lineHeight: 1.4 }}>
                                                                {item.label}
                                                            </div>
                                                            {item.detail && (
                                                                <div style={{ fontSize: '10.5px', color: 'var(--text-muted)', marginTop: '2px', lineHeight: 1.35 }}>
                                                                    {item.detail}
                                                                </div>
                                                            )}
                                                            {item.tag && (
                                                                <span style={{ display: 'inline-block', marginTop: '4px', fontSize: '10px', fontFamily: 'monospace', padding: '1px 5px', borderRadius: '3px', ...tagStyle }}>
                                                                    {item.tag === 'critical' ? '🔴 Kritisch' : item.tag === 'important' ? '⚡ Wichtig' : 'Standard'}
                                                                </span>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                );
            })}
        </div>
    );
};

export default ChecklistEditor;
