import * as React from 'react';
import { Check, X } from 'lucide-react';
import { cn } from '../../shared/utils';

interface StepperContextValue {
  currentStep: number;
  totalSteps: number;
  orientation: 'horizontal' | 'vertical';
}

const StepperContext = React.createContext<StepperContextValue | undefined>(undefined);

const useStepperContext = () => {
  const context = React.useContext(StepperContext);
  if (!context) throw new Error('useStepperContext must be used within a Stepper');
  return context;
};

interface StepperProps extends React.HTMLAttributes<HTMLDivElement> {
  currentStep: number;
  /** Layout direction. @default "horizontal" */
  orientation?: 'horizontal' | 'vertical';
}

/**
 * Multi-step progress indicator for sequential forms and wizards.
 *
 * @description
 * Guides the user through a linear multi-step flow. Supports horizontal (default)
 * and vertical orientations. Steps before `currentStep` show as completed (checkmark),
 * the current step as active (primary), error steps show an X, and future steps as pending (muted).
 *
 * @ai-rules
 * 1. `step` props are 1-indexed — the first step is `step={1}`, not `step={0}`.
 * 2. Control the active step with `currentStep` on `<Stepper>` (1-indexed).
 * 3. Validate the current step's form data BEFORE advancing `currentStep`.
 * 4. Use `error={true}` on a `<Step>` to indicate a validation failure on that step.
 */
const Stepper = React.forwardRef<HTMLDivElement, StepperProps>(
  ({ currentStep, orientation = 'horizontal', className, children, ...props }, ref) => {
    const totalSteps = React.Children.count(children);

    return (
      <StepperContext.Provider value={{ currentStep, totalSteps, orientation }}>
        <div ref={ref} className={cn('w-full', className)} {...props}>
          <div
            className={cn(
              orientation === 'horizontal'
                ? 'flex items-start justify-between'
                : 'flex flex-col gap-0'
            )}
            role="list"
            aria-label={`Progresso: etapa ${currentStep} de ${totalSteps}`}
          >
            {children}
          </div>
        </div>
      </StepperContext.Provider>
    );
  }
);
Stepper.displayName = 'Stepper';

interface StepProps extends React.HTMLAttributes<HTMLDivElement> {
  step: number;
  label: string;
  description?: string;
  /** Marks this step as having a validation error. Renders a red X icon. */
  error?: boolean;
}

const Step = React.forwardRef<HTMLDivElement, StepProps>(
  ({ step, label, description, error = false, className, ...props }, ref) => {
    const { currentStep, totalSteps, orientation } = useStepperContext();
    const isActive = step === currentStep;
    const isCompleted = step < currentStep && !error;
    const isFirst = step === 1;
    const isLast = step === totalSteps;

    const circleClasses = cn(
      'relative flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border-2 transition-colors',
      isActive && !error && 'border-primary bg-primary text-primary-foreground',
      isCompleted && 'border-primary bg-primary text-primary-foreground',
      error && 'border-destructive bg-destructive text-destructive-foreground',
      !isActive && !isCompleted && !error && 'border-muted bg-background text-muted-foreground'
    );

    const connectorClasses = (filled: boolean) =>
      cn('transition-colors', filled ? 'bg-primary' : 'bg-muted');

    if (orientation === 'vertical') {
      return (
        <div
          ref={ref}
          className={cn('flex gap-4', className)}
          role="listitem"
          aria-current={isActive ? 'step' : undefined}
          aria-label={`Etapa ${step}: ${label}${isCompleted ? ', concluída' : isActive ? ', atual' : ''}`}
          {...props}
        >
          {/* Left column: circle + vertical line */}
          <div className="flex flex-col items-center">
            <div className={circleClasses}>
              {error ? (
                <X className="h-5 w-5" />
              ) : isCompleted ? (
                <Check className="h-5 w-5" />
              ) : (
                <span>{step}</span>
              )}
            </div>
            {!isLast && (
              <div
                className={cn(
                  'w-0.5 flex-1 min-h-[2rem] mt-1',
                  connectorClasses(step < currentStep)
                )}
              />
            )}
          </div>
          {/* Right column: label + description */}
          <div className={cn('pb-6', isLast && 'pb-0')}>
            <div
              className={cn(
                'transition-colors',
                isActive || error ? 'text-foreground' : 'text-muted-foreground'
              )}
            >
              {label}
            </div>
            {description && <div className="mt-1 text-xs text-muted-foreground">{description}</div>}
          </div>
        </div>
      );
    }

    // Horizontal layout (default)
    return (
      <div
        ref={ref}
        className={cn('flex flex-1 flex-col items-center', className)}
        role="listitem"
        aria-current={isActive ? 'step' : undefined}
        aria-label={`Etapa ${step}: ${label}${isCompleted ? ', concluída' : isActive ? ', atual' : ''}`}
        {...props}
      >
        {/* Circle and connector */}
        <div className="flex w-full items-start">
          {step > 1 && (
            <div className={cn('h-0.5 flex-1 mt-[18px]', connectorClasses(step <= currentStep))} />
          )}
          <div className={circleClasses}>
            {error ? (
              <X className="h-5 w-5" />
            ) : isCompleted ? (
              <Check className="h-5 w-5" />
            ) : (
              <span>{step}</span>
            )}
          </div>
          {step < totalSteps && (
            <div className={cn('h-0.5 flex-1 mt-[18px]', connectorClasses(step < currentStep))} />
          )}
        </div>
        {/* Label */}
        <div
          className={cn(
            'mt-2 px-1',
            isFirst && 'text-left self-start',
            isLast && 'text-right self-end',
            !isFirst && !isLast && 'text-center w-full'
          )}
        >
          <div
            className={cn(
              'transition-colors',
              isActive || error ? 'text-foreground' : 'text-muted-foreground'
            )}
          >
            {label}
          </div>
          {description && <div className="mt-1 text-xs text-muted-foreground">{description}</div>}
        </div>
      </div>
    );
  }
);
Step.displayName = 'Step';

export { Stepper, Step, useStepperContext };
