import React from 'react';
import { __ } from '@wordpress/i18n';

const COLORS = {
    completed: '#39758D',
    current:   '#ED7D31',
    available: '#6B7280',
    locked:    '#D1D5DB',
    error:     '#DC2626',
    skipped:   '#9CA3AF',
};

// Visible step numbering is sequential (1..N) — independent of the underlying
// 13-step spec numbers. Custom Fields (8) and Activity (10) are dropped from
// the navbar; the wizard panel still routes through them (Continue buttons
// pass setStep('custom-fields')), the stepper just doesn't show them as nodes.
const buildSteps = () => [
    { id: 'upload',         num: 1,  label: __('Upload',    'lazytasks-project-task-management'), foldsIn: ['preview'] },
    { id: 'workspace',      num: 2,  label: __('Workspace', 'lazytasks-project-task-management') },
    { id: 'project-entry',  num: 3,  label: __('Project',   'lazytasks-project-task-management') },
    { id: 'member-mapping', num: 4,  label: __('Members',   'lazytasks-project-task-management') },
    { id: 'sections',       num: 5,  label: __('Sections',  'lazytasks-project-task-management') },
    { id: 'settings',       num: 6,  label: __('Settings',  'lazytasks-project-task-management') },
    { id: 'tags',           num: 7,  label: __('Tags',      'lazytasks-project-task-management') },
    { id: 'tasks',          num: 8,  label: __('Tasks',     'lazytasks-project-task-management') },
    { id: 'review',         num: 9,  label: __('Review',    'lazytasks-project-task-management') },
    { id: 'importing',      num: 10, label: __('Import',    'lazytasks-project-task-management') },
    { id: 'results',        num: 11, label: __('Done',      'lazytasks-project-task-management') },
];

const TrelloImportStepper = ({
    currentStep,
    visitedSteps = [],
    activityLogLevel = 'off',
    linkState,
    onStepClick,
}) => {
    // Conflict banners block the wizard entirely — no stepper there
    if (
        currentStep === 'upload' &&
        (linkState?.status === 'conflict_completed' || linkState?.status === 'conflict_other_user')
    ) {
        return null;
    }

    const STEPS = buildSteps();

    // 'preview' folds into 'upload' for the navbar — they share the same node
    const resolvedCurrent = STEPS.find(
        (s) => s.id === currentStep || (s.foldsIn || []).includes(currentStep)
    );
    const currentIdx = resolvedCurrent ? STEPS.indexOf(resolvedCurrent) : 0;

    const isVisited = (s) =>
        visitedSteps.includes(s.id) ||
        (s.foldsIn || []).some((id) => visitedSteps.includes(id));

    const computeState = (s, idx) => {
        if (
            s.conditional &&
            s.id === 'activity' &&
            activityLogLevel === 'off' &&
            idx !== currentIdx
        ) {
            return 'skipped';
        }
        if (idx === currentIdx) return 'current';
        if (idx < currentIdx) return 'completed';
        return isVisited(s) ? 'available' : 'locked';
    };

    const isClickable = (state) =>
        (state === 'completed' || state === 'available') &&
        typeof onStepClick === 'function';

    const nodeIcon = (state, num) => {
        if (state === 'completed') return '✓';
        if (state === 'error')     return '!';
        if (state === 'skipped')   return '⊘';
        return num;
    };

    return (
        <div
            role="navigation"
            aria-label={__('Trello import progress', 'lazytasks-project-task-management')}
            style={{
                display: 'flex',
                alignItems: 'flex-start',
                justifyContent: 'space-between',
                gap: 4,
                padding: '12px 8px 20px',
                marginBottom: 16,
                overflowX: 'auto',
                borderBottom: '1px solid #E5E7EB',
            }}
        >
            {STEPS.map((s, idx) => {
                const state = computeState(s, idx);
                const clickable = isClickable(state);
                const isLast = idx === STEPS.length - 1;
                const color = COLORS[state];
                const isCurrent = state === 'current';

                return (
                    <React.Fragment key={s.id}>
                        <div
                            style={{
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                minWidth: 60,
                                flex: '0 0 auto',
                            }}
                        >
                            <button
                                type="button"
                                onClick={clickable ? () => onStepClick(s.id) : undefined}
                                disabled={!clickable}
                                aria-current={isCurrent ? 'step' : undefined}
                                aria-label={`${__('Step', 'lazytasks-project-task-management')} ${s.num}: ${s.label}`}
                                title={s.label}
                                style={{
                                    width: isCurrent ? 32 : 26,
                                    height: isCurrent ? 32 : 26,
                                    borderRadius: '50%',
                                    background: state === 'locked' ? '#FFFFFF' : color,
                                    border: `2px solid ${color}`,
                                    color: state === 'locked' ? color : '#FFFFFF',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    fontSize: 12,
                                    fontWeight: 700,
                                    cursor: clickable ? 'pointer' : 'not-allowed',
                                    padding: 0,
                                    transition: 'all .2s ease',
                                    boxShadow: isCurrent ? `0 0 0 4px ${color}33` : 'none',
                                    opacity: state === 'skipped' ? 0.6 : 1,
                                    lineHeight: 1,
                                }}
                            >
                                {nodeIcon(state, s.num)}
                            </button>
                            <div
                                style={{
                                    marginTop: 6,
                                    fontSize: 11,
                                    fontWeight: isCurrent ? 600 : 500,
                                    color: isCurrent
                                        ? COLORS.current
                                        : state === 'locked'
                                            ? '#9CA3AF'
                                            : '#374151',
                                    textAlign: 'center',
                                    whiteSpace: 'nowrap',
                                    opacity: state === 'skipped' ? 0.6 : 1,
                                }}
                            >
                                {s.label}
                            </div>
                        </div>

                        {!isLast && (
                            <div
                                aria-hidden="true"
                                style={{
                                    flex: 1,
                                    height: 2,
                                    background: idx < currentIdx ? COLORS.completed : COLORS.locked,
                                    marginTop: 14,
                                    minWidth: 12,
                                }}
                            />
                        )}
                    </React.Fragment>
                );
            })}
        </div>
    );
};

export default TrelloImportStepper;
