import { useState, ReactNode } from "react";
import CheckIcon from "@app/assets/images/check-icon.svg";

import "./stepper-styles.scss";

interface Step {
  title: string;
  header: string;
  action: {
    label: string;
    url: string;
    icon: ReactNode;
    target?: string;
  };
  content: ReactNode;
  isDone?: boolean;
}

interface StepperProps {
  steps: Step[];
}

export default function Stepper({ steps = [] }: StepperProps) {
  const safeSteps = Array.isArray(steps) ? steps : [];
  const firstIncompleteIndex = safeSteps.findIndex((step) => !step.isDone);

  const [currentStep, setCurrentStep] = useState<number>(() => {
    if (firstIncompleteIndex !== -1) {
      return firstIncompleteIndex;
    } else if (safeSteps.length > 0) {
      return safeSteps.length - 1;
    } else {
      return 0;
    }
  });

  // If no steps are provided, show a message
  if (safeSteps.length === 0) {
    return <div className="stepper-empty">No steps provided</div>;
  }

  return (
    <div className="stepper-container">
      <div className="stepper-header">
        {safeSteps.map((step, index) => (
          <div
            key={index}
            className="stepper-step"
            style={{ width: `${100 / safeSteps.length}%` }}
          >
            {index < safeSteps.length - 1 && <div className="stepper-line" />}

            {step.isDone ? (
              <img src={CheckIcon} alt="Check Icon" width={"10px"} />
            ) : (
              <div
                className={`stepper-circle ${
                  index < currentStep
                    ? "completed"
                    : index === currentStep
                    ? "active"
                    : ""
                }`}
              ></div>
            )}

            <div className="stepper-title">{step.title}</div>
          </div>
        ))}
      </div>

      <div className="stepper-content">
        <h2>{safeSteps[currentStep]?.header}</h2>
        {safeSteps[currentStep]?.content || <div>No content available</div>}
      </div>

      <div className="stepper-navigation">
        <a
          href={safeSteps[currentStep]?.action.url}
          className="stepper-btn"
          target={
            safeSteps[currentStep]?.action.target
              ? safeSteps[currentStep]?.action.target
              : "_self"
          }
        >
          {safeSteps[currentStep]?.action.label ?? "Done"}
          {safeSteps[currentStep]?.action.icon && (
            <div className="stepper-btn-icon">
              {safeSteps[currentStep]?.action.icon}
            </div>
          )}
        </a>
      </div>
    </div>
  );
}
