import React, { useMemo } from "react";

type Step = {
  id: string;
  label: string;
  description?: string;
  icon?: React.ReactNode;
};

type StepperProps = {
  steps: Step[];
  currentStep: string;
};

export const Stepper: React.FC<StepperProps> = ({ steps, currentStep }) => {
  const stepIndex = useMemo(
    () => steps.findIndex((s) => s.id === currentStep),
    [currentStep, steps],
  );

  const percent = useMemo(() => {
    return steps.length === 1
      ? 100
      : Math.round((stepIndex / (steps.length - 1)) * 100);
  }, [stepIndex, steps.length]);

  return (
    <div className="flex flex-col sm:flex-row sm:items-center w-full max-w-2xl mx-auto mb-5 sm:mb-8 gap-5 relative">
      {steps.map((step, idx) => (
        <div
          key={idx}
          className={`sm:flex p-4 pb-0 sm:p-0 flex-1 items-center ${idx < stepIndex ? "opacity-70" : ""} ${idx === stepIndex ? "flex" : "hidden"}`}
        >
          {/* Step circle */}
          <div
            className={`relative z-10 flex items-center justify-center w-12 h-12 min-w-12 sm:w-10 sm:h-10 sm:min-w-10 rounded-full
                        ${
                          idx < stepIndex
                            ? "bg-blue-400 text-white"
                            : idx === stepIndex
                              ? "bg-blue-600 text-white"
                              : "bg-gray-100 dark:bg-gray-800/60 text-gray-500"
                        }
                      `}
          >
            {idx < stepIndex ? (
              // Check icon for completed steps
              <svg
                className="w-5 h-5"
                fill="none"
                stroke="currentColor"
                strokeWidth={3}
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M5 13l4 4L19 7"
                />
              </svg>
            ) : (
              (step.icon ?? <span className="font-bold">{idx + 1}</span>)
            )}
          </div>

          {/* Step label */}
          <div className="flex flex-col ml-2 mr-2 sm:ml-4 sm:mr-4">
            <span className="text-base text-gray-700 dark:text-gray-200 sm:text-sm font-medium">
              {step.label}
            </span>
            {step.description && (
              <span className="text-sm sm:text-xs text-gray-500 dark:text-gray-400">
                {step.description}
              </span>
            )}
          </div>

          {/* {idx < steps.length - 1 && (
              <div className="flex-1 h-1 mx-2 min-w sm:mx-4 rounded bg-gray-300 dark:bg-gray-600" />
            )} */}
        </div>
      ))}
      <div className="sm:hidden relative h-1 w-full bg-gray-200 dark:bg-gray-700 overflow-hidden">
        <div
          className="absolute left-0 top-0 h-full bg-blue-500 transition-all ease-in duration-500"
          style={{ width: `${percent}%` }}
        />
      </div>
    </div>
  );
};
