'use client';

import { CheckCircle, ArrowRight, ArrowLeft } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';

interface OnboardingStep {
  id: string;
  title: string;
  description: string;
  component: React.ComponentType<{ onComplete: () => void }>;
}

interface OnboardingWizardProps {
  steps: OnboardingStep[];
  onComplete: () => Promise<void>;
}

export function OnboardingWizard({ steps, onComplete }: OnboardingWizardProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const [completedSteps, setCompletedSteps] = useState<Set<string>>(new Set());
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  const handleNext = async () => {
    setError(null);

    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
    } else {
      try {
        setSubmitting(true);
        await onComplete();
        router.push('/dashboard');
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unable to complete onboarding.');
      } finally {
        setSubmitting(false);
      }
    }
  };

  const handlePrevious = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleStepComplete = (stepId: string) => {
    setCompletedSteps(new Set([...completedSteps, stepId]));
  };

  const CurrentStepComponent = steps[currentStep].component;

  return (
    <div className="fixed inset-0 z-50 bg-gray-900/95 backdrop-blur flex items-center justify-center p-4">
      <Card className="bg-gray-800 border-gray-700 max-w-4xl w-full">
        <CardHeader>
          <div className="mb-6">
            <div className="flex items-center justify-between mb-4">
              <CardTitle className="text-white text-2xl">
                Welcome to Nexus Console
              </CardTitle>
              <span className="text-sm text-gray-400">
                Step {currentStep + 1} of {steps.length}
              </span>
            </div>
            
            {/* Progress bar */}
            <div className="w-full bg-gray-900 rounded-full h-2">
              <div
                className="bg-orange-500 h-2 rounded-full transition-all"
                style={{ width: `${((currentStep + 1) / steps.length) * 100}%` }}
              />
            </div>
          </div>

          {/* Step indicators */}
          <div className="flex items-center justify-between mb-6">
            {steps.map((step, index) => (
              <div key={step.id} className="flex items-center flex-1">
                <div className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center border-2 ${
                      index < currentStep
                        ? 'bg-green-500 border-green-500'
                        : index === currentStep
                        ? 'bg-orange-500 border-orange-500'
                        : 'bg-gray-700 border-gray-600'
                    }`}
                  >
                    {index < currentStep ? (
                      <CheckCircle className="h-6 w-6 text-white" />
                    ) : (
                      <span className="text-white font-semibold">{index + 1}</span>
                    )}
                  </div>
                  <span className="text-xs text-gray-400 mt-2 text-center max-w-20">
                    {step.title}
                  </span>
                </div>
                {index < steps.length - 1 && (
                  <div
                    className={`flex-1 h-0.5 mx-2 ${
                      index < currentStep ? 'bg-green-500' : 'bg-gray-700'
                    }`}
                  />
                )}
              </div>
            ))}
          </div>
        </CardHeader>
        <CardContent>
          <div className="mb-6">
            <h3 className="text-xl font-semibold text-white mb-2">
              {steps[currentStep].title}
            </h3>
            <p className="text-gray-400 mb-6">
              {steps[currentStep].description}
            </p>
            {error ? (
              <div className="mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300">
                {error}
              </div>
            ) : null}
            <CurrentStepComponent
              onComplete={() => handleStepComplete(steps[currentStep].id)}
            />
          </div>

          <div className="flex items-center justify-between pt-4 border-t border-gray-700">
            <button
              onClick={handlePrevious}
              disabled={currentStep === 0}
              className="px-6 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              <ArrowLeft className="h-4 w-4" />
              Previous
            </button>
            <button
              onClick={handleNext}
              disabled={submitting}
              className="px-6 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors flex items-center gap-2"
            >
              {submitting ? 'Saving...' : currentStep === steps.length - 1 ? 'Complete' : 'Next'}
              <ArrowRight className="h-4 w-4" />
            </button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
