/**
 * Multi-Step Form Wrapper
 * Reusable component for multi-step forms with progress indication
 */

"use client";

import { useEffect, type ReactNode } from "react";
import { Button } from "@/components/atoms";

export interface FormStep {
  key: string;
  title: string;
  description: string;
  content: ReactNode;
  isValid?: boolean;
}

interface MultiStepFormProps {
  steps: FormStep[];
  currentStep: number;
  onNext: () => void;
  onPrevious: () => void;
  isLastStep: boolean;
  isSubmitting?: boolean;
  canProceed?: boolean;
  onStepChange?: (stepIndex: number) => void;
  className?: string;
}

export function MultiStepForm({
  steps,
  currentStep,
  onNext,
  onPrevious,
  isLastStep,
  isSubmitting = false,
  canProceed = true,
  onStepChange,
  className = "",
}: MultiStepFormProps) {
  useEffect(() => {
    onStepChange?.(currentStep);
  }, [currentStep, onStepChange]);

  const totalSteps = steps.length;
  const step = steps[currentStep] ?? steps[0];
  const progress = totalSteps > 0 ? ((currentStep + 1) / totalSteps) * 100 : 0;
  const isFirstStep = currentStep === 0;
  const disableNext = isSubmitting || (!canProceed && !isLastStep);

  return (
    <div className={`space-y-6 ${className}`}>
      <div className="space-y-2">
        <div className="flex justify-between text-sm text-gray-600">
          <span>
            Step {Math.min(currentStep + 1, totalSteps)} of {totalSteps}
          </span>
          <span>{Math.round(progress)}% Complete</span>
        </div>
        <div className="w-full bg-gray-200 rounded-full h-2">
          <div
            className="bg-blue-600 h-2 rounded-full transition-all duration-300"
            style={{ width: `${progress}%` }}
          />
        </div>
        <div className="text-center">
          <h3 className="text-lg font-semibold text-gray-900">{step?.title}</h3>
          <p className="text-sm text-gray-600">{step?.description}</p>
        </div>
      </div>

      <div className="min-h-[400px]">{step?.content}</div>

      <div className="flex justify-between space-x-4">
        <Button
          type="button"
          variant="outline"
          onClick={onPrevious}
          disabled={isFirstStep || isSubmitting}
          className="flex-1"
        >
          Previous
        </Button>

        <Button
          type="button"
          variant="default"
          onClick={onNext}
          disabled={disableNext}
          loading={isSubmitting && isLastStep}
          className="flex-1"
        >
          {isLastStep ? (isSubmitting ? "Creating Account..." : "Create Account") : "Next"}
        </Button>
      </div>
    </div>
  );
}
