import { Fragment } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';
import {
  STEPPER_ACTIVE_BG,
  STEPPER_ACTIVE_NUMBER,
  STEPPER_CIRCLE_BASE_STYLE,
  STEPPER_COMPLETED_BORDER,
  STEPPER_COMPLETED_FILL,
  STEPPER_COMPLETED_ICON,
  STEPPER_DEFAULT_MAX_WIDTH,
  STEPPER_INACTIVE_BG,
  STEPPER_LABEL_ACTIVE,
  STEPPER_LABEL_INACTIVE,
  STEPPER_LINE,
  STEPPER_STEP_LABEL_STYLE,
  getStepperGridTemplateColumns,
} from './stepperStyles';

/**
 * Stepper horizontal (spec relación laboral / AltaEdicionPersonas).
 * Pasos con número o check, etiquetas y conectores entre círculos.
 *
 * @param {Array<{ label: string, key?: string }>} steps
 * @param {number} [currentStep] — índice activo (0-based).
 * @param {string} [ariaLabel] — Accesibilidad del `<nav>`.
 * @param {boolean} [showStepLabels] — Muestra texto junto al círculo (default true).
 * @param {boolean} [hideStepLabelsOnMobile] — Oculta etiquetas en viewport &lt; 768px.
 * @param {string} [maxWidth] — Ancho máximo del contenedor.
 * @param {string} [className] — Clase del `<nav>`.
 * @param {object} [style] — Estilos del `<nav>`.
 * @param {string} [wrapClassName] — Clase del contenedor exterior.
 * @param {object} [wrapStyle] — Estilos del contenedor exterior.
 */
export const Stepper = ({
  steps = [],
  currentStep = 0,
  ariaLabel = 'Pasos',
  showStepLabels = true,
  hideStepLabelsOnMobile = false,
  maxWidth = STEPPER_DEFAULT_MAX_WIDTH,
  className = '',
  style,
  wrapClassName = '',
  wrapStyle,
  ...props
}) => {
  if (!Array.isArray(steps) || steps.length === 0) return null;

  const safeCurrent = Math.min(Math.max(0, currentStep), steps.length - 1);

  const wrapClasses = [
    'anima-stepper__wrap',
    hideStepLabelsOnMobile ? 'anima-stepper--hide-labels-mobile' : '',
    wrapClassName,
  ]
    .filter(Boolean)
    .join(' ');

  return (
    <div
      className={wrapClasses}
      style={{
        maxWidth,
        width: '100%',
        marginLeft: 'auto',
        marginRight: 'auto',
        boxSizing: 'border-box',
        ...wrapStyle,
      }}
    >
      {hideStepLabelsOnMobile ? (
        <style>{`
          @media (max-width: 767px) {
            .anima-stepper--hide-labels-mobile .anima-stepper__step-label {
              display: none !important;
            }
            .anima-stepper--hide-labels-mobile.anima-stepper__wrap {
              padding-left: 16px;
              padding-right: 16px;
              box-sizing: border-box;
            }
          }
        `}</style>
      ) : null}
      <nav
        className={`anima-stepper ${className}`.trim()}
        aria-label={ariaLabel}
        style={{ width: '100%', ...style }}
        {...props}
      >
        <ol
          style={{
            display: 'grid',
            gridTemplateColumns: getStepperGridTemplateColumns(steps.length),
            alignItems: 'center',
            columnGap: '8px',
            width: '100%',
            listStyle: 'none',
            margin: 0,
            padding: 0,
          }}
        >
          {steps.map((step, index) => {
            const isActive = index === safeCurrent;
            const isCompleted = index < safeCurrent;
            const labelColor = isActive || isCompleted ? STEPPER_LABEL_ACTIVE : STEPPER_LABEL_INACTIVE;
            const labelWeight = isActive || isCompleted ? 600 : 400;
            const stepNumberColor = isActive ? STEPPER_ACTIVE_NUMBER : STEPPER_LABEL_INACTIVE;
            const stepKey = step.key ?? step.label ?? index;

            const stepCircleStyle = {
              ...STEPPER_CIRCLE_BASE_STYLE,
              ...(isActive
                ? {
                    backgroundColor: STEPPER_ACTIVE_BG,
                    border: '2px solid transparent',
                    color: stepNumberColor,
                  }
                : isCompleted
                  ? {
                      backgroundColor: STEPPER_COMPLETED_FILL,
                      border: `2px solid ${STEPPER_COMPLETED_BORDER}`,
                    }
                  : {
                      backgroundColor: STEPPER_INACTIVE_BG,
                      border: '2px solid transparent',
                      color: stepNumberColor,
                    }),
            };

            return (
              <Fragment key={stepKey}>
                <li aria-label={step.label} style={{ minWidth: 0, margin: 0, padding: 0 }}>
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: '8px',
                      minWidth: 0,
                    }}
                  >
                    <span style={stepCircleStyle} aria-current={isActive ? 'step' : undefined}>
                      {isCompleted ? (
                        <Icon
                          name="CheckIcon"
                          variant="24-outline"
                          size={18}
                          style={{ color: STEPPER_COMPLETED_ICON, flexShrink: 0 }}
                          aria-hidden
                        />
                      ) : (
                        index + 1
                      )}
                    </span>
                    {showStepLabels && step.label ? (
                      <span
                        className="anima-stepper__step-label"
                        style={{
                          ...STEPPER_STEP_LABEL_STYLE,
                          fontWeight: labelWeight,
                          color: labelColor,
                        }}
                      >
                        {step.label}
                      </span>
                    ) : null}
                  </div>
                </li>
                {index < steps.length - 1 ? (
                  <li
                    aria-hidden="true"
                    style={{
                      display: 'block',
                      minWidth: 0,
                      margin: 0,
                      padding: 0,
                      listStyle: 'none',
                      alignSelf: 'center',
                    }}
                  >
                    <div
                      style={{
                        width: '100%',
                        height: '2px',
                        backgroundColor: STEPPER_LINE,
                      }}
                    />
                  </li>
                ) : null}
              </Fragment>
            );
          })}
        </ol>
      </nav>
    </div>
  );
};

export default Stepper;
