import React, { useState, useEffect, useRef } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { CheckCircle, Mail, Lock, User, Building2, CreditCard, ArrowRight, ArrowLeft, Loader, Database, Settings, Sparkles } from 'lucide-react';
import { useInvitationByToken, useAcceptInvitation } from '../hooks/usePlatform';
import { getBaseDomain, buildSubdomainUrl } from '../utils/domain';

// Loading step configuration for the animated progress
// The last step stays active (spinning) until the API returns
const LOADING_STEPS = [
  { id: 'account', label: 'Creating your account', icon: User, duration: 2000 },
  { id: 'database', label: 'Setting up your database', icon: Database, duration: 8000 },
  { id: 'config', label: 'Configuring your workspace', icon: Settings, duration: 6000 },
  { id: 'migrations', label: 'Running database migrations', icon: Database, duration: 15000 },
  { id: 'features', label: 'Activating features', icon: Sparkles, duration: null }, // null = stays spinning until done
];

const TenantOnboardPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = searchParams.get('token');

  const { data: invitation, isLoading, error } = useInvitationByToken(token);
  const acceptInvitationMutation = useAcceptInvitation();

  const [currentStep, setCurrentStep] = useState(1);
  const [isCreating, setIsCreating] = useState(false);
  const [creationComplete, setCreationComplete] = useState(false);
  const [loadingStepIndex, setLoadingStepIndex] = useState(0);
  const [elapsedSeconds, setElapsedSeconds] = useState(0);
  const loadingIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const elapsedTimerRef = useRef<NodeJS.Timeout | null>(null);
  const [formData, setFormData] = useState({
    // Step 1: Account
    email: '',
    password: '',
    confirmPassword: '',
    first_name: '',
    last_name: '',
    // Step 2: Business
    business_name: '',
    subdomain: '',
    contact_email: '',
    phone: '',
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [acceptError, setAcceptError] = useState<string | null>(null);

  // Pre-fill email and business name from invitation
  useEffect(() => {
    if (invitation) {
      setFormData(prev => ({
        ...prev,
        email: invitation.email,
        business_name: invitation.suggested_business_name || '',
        contact_email: invitation.email,
        subdomain: invitation.suggested_business_name
          ? invitation.suggested_business_name.toLowerCase().replace(/[^a-z0-9-]/g, '').substring(0, 20)
          : '',
      }));
    }
  }, [invitation]);

  const validateStep1 = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Invalid email address';
    }

    if (!formData.password) {
      newErrors.password = 'Password is required';
    } else if (formData.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
    }

    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match';
    }

    if (!formData.first_name.trim()) {
      newErrors.first_name = 'First name is required';
    }

    if (!formData.last_name.trim()) {
      newErrors.last_name = 'Last name is required';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const validateStep2 = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.business_name.trim()) {
      newErrors.business_name = 'Business name is required';
    }

    if (!formData.subdomain.trim()) {
      newErrors.subdomain = 'Subdomain is required';
    } else if (!/^[a-z][a-z0-9-]*$/.test(formData.subdomain)) {
      newErrors.subdomain = 'Subdomain must start with a letter and contain only lowercase letters, numbers, and hyphens';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNext = () => {
    if (currentStep === 1 && !validateStep1()) {
      return;
    }
    if (currentStep === 2 && !validateStep2()) {
      return;
    }

    // Skip payment step if not enabled
    if (currentStep === 2 && !invitation?.permissions?.can_accept_payments) {
      handleSubmit();
      return;
    }

    setCurrentStep(prev => prev + 1);
  };

  const handleBack = () => {
    setCurrentStep(prev => prev - 1);
  };

  // Cleanup timers on unmount
  useEffect(() => {
    return () => {
      if (loadingIntervalRef.current) {
        clearTimeout(loadingIntervalRef.current);
      }
      if (elapsedTimerRef.current) {
        clearInterval(elapsedTimerRef.current);
      }
    };
  }, []);

  // Animate through loading steps
  const startLoadingAnimation = () => {
    setLoadingStepIndex(0);
    setElapsedSeconds(0);
    let stepIndex = 0;

    // Start elapsed time counter
    elapsedTimerRef.current = setInterval(() => {
      setElapsedSeconds(prev => prev + 1);
    }, 1000);

    const advanceStep = () => {
      stepIndex++;
      if (stepIndex < LOADING_STEPS.length) {
        setLoadingStepIndex(stepIndex);
        const nextDuration = LOADING_STEPS[stepIndex].duration;
        // If duration is null, this step stays active until API returns
        if (nextDuration !== null) {
          loadingIntervalRef.current = setTimeout(advanceStep, nextDuration);
        }
      }
    };

    const firstDuration = LOADING_STEPS[0].duration;
    if (firstDuration !== null) {
      loadingIntervalRef.current = setTimeout(advanceStep, firstDuration);
    }
  };

  const stopLoadingAnimation = () => {
    if (loadingIntervalRef.current) {
      clearTimeout(loadingIntervalRef.current);
    }
    if (elapsedTimerRef.current) {
      clearInterval(elapsedTimerRef.current);
    }
  };

  const handleSubmit = () => {
    if (!token) return;

    setAcceptError(null);
    setIsCreating(true);
    startLoadingAnimation();

    const data = {
      email: formData.email,
      password: formData.password,
      first_name: formData.first_name,
      last_name: formData.last_name,
      business_name: formData.business_name,
      subdomain: formData.subdomain,
      contact_email: formData.contact_email || formData.email,
      phone: formData.phone || undefined,
    };

    acceptInvitationMutation.mutate(
      { token, data },
      {
        onSuccess: () => {
          stopLoadingAnimation();
          // Show all steps as complete, then show success
          setLoadingStepIndex(LOADING_STEPS.length);
          setTimeout(() => {
            setIsCreating(false);
            setCreationComplete(true);
          }, 500);
        },
        onError: (error: any) => {
          stopLoadingAnimation();
          setIsCreating(false);
          setAcceptError(
            error.response?.data?.detail ||
            error.response?.data?.subdomain?.[0] ||
            error.message ||
            'Failed to accept invitation'
          );
        },
      }
    );
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-indigo-50 to-blue-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center">
        <div className="text-center">
          <Loader className="w-12 h-12 animate-spin text-indigo-600 mx-auto mb-4" />
          <p className="text-gray-600 dark:text-gray-400">Loading invitation...</p>
        </div>
      </div>
    );
  }

  if (error || !invitation) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-indigo-50 to-blue-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-8 max-w-md w-full text-center">
          <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
            <span className="text-3xl">❌</span>
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">Invalid Invitation</h2>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            This invitation link is invalid or has expired.
          </p>
          <button
            onClick={() => navigate('/')}
            className="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
          >
            Go to Home
          </button>
        </div>
      </div>
    );
  }

  const totalSteps = invitation.permissions?.can_accept_payments ? 4 : 3;

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 to-blue-50 dark:from-gray-900 dark:to-gray-800 py-12 px-4">
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            Welcome to SmoothSchedule
          </h1>
          <p className="text-gray-600 dark:text-gray-400">
            Complete your business setup to get started
          </p>
        </div>

        {/* Progress Steps */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            {[1, 2, totalSteps === 4 ? 3 : null, totalSteps].filter(Boolean).map((step, idx, arr) => (
              <React.Fragment key={step}>
                <div className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center ${
                      currentStep >= (step || 0)
                        ? 'bg-indigo-600 text-white'
                        : 'bg-gray-300 dark:bg-gray-600 text-gray-600 dark:text-gray-400'
                    }`}
                  >
                    {currentStep > (step || 0) ? <CheckCircle size={20} /> : step}
                  </div>
                  <span className="text-xs mt-2 text-gray-600 dark:text-gray-400">
                    {step === 1 && 'Account'}
                    {step === 2 && 'Business'}
                    {step === 3 && totalSteps === 4 && 'Payment'}
                    {step === totalSteps && 'Complete'}
                  </span>
                </div>
                {idx < arr.length - 1 && (
                  <div
                    className={`flex-1 h-1 mx-2 ${
                      currentStep > (step || 0) ? 'bg-indigo-600' : 'bg-gray-300 dark:bg-gray-600'
                    }`}
                  />
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* Content Card */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-8">
          {acceptError && (
            <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
              <p className="text-sm text-red-600 dark:text-red-400">{acceptError}</p>
            </div>
          )}

          {/* Step 1: Account Setup */}
          {currentStep === 1 && !isCreating && !creationComplete && (
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                  Create Your Account
                </h2>
                <p className="text-gray-600 dark:text-gray-400">
                  You've been invited to create a <strong>{invitation.subscription_tier}</strong> business
                  with up to {invitation.effective_max_users} users and {invitation.effective_max_resources} resources.
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Email Address
                </label>
                <div className="relative">
                  <Mail size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                  <input
                    type="email"
                    value={formData.email}
                    readOnly
                    className="w-full pl-10 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    First Name *
                  </label>
                  <div className="relative">
                    <User size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                    <input
                      type="text"
                      value={formData.first_name}
                      onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                      className={`w-full pl-10 pr-4 py-3 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
                        errors.first_name ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                      }`}
                    />
                  </div>
                  {errors.first_name && <p className="text-red-500 text-xs mt-1">{errors.first_name}</p>}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Last Name *
                  </label>
                  <input
                    type="text"
                    value={formData.last_name}
                    onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                    className={`w-full px-4 py-3 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
                      errors.last_name ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                    }`}
                  />
                  {errors.last_name && <p className="text-red-500 text-xs mt-1">{errors.last_name}</p>}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Password *
                </label>
                <div className="relative">
                  <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                  <input
                    type="password"
                    value={formData.password}
                    onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                    className={`w-full pl-10 pr-4 py-3 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
                      errors.password ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                    }`}
                    placeholder="Min. 8 characters"
                  />
                </div>
                {errors.password && <p className="text-red-500 text-xs mt-1">{errors.password}</p>}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Confirm Password *
                </label>
                <div className="relative">
                  <Lock size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                  <input
                    type="password"
                    value={formData.confirmPassword}
                    onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                    className={`w-full pl-10 pr-4 py-3 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
                      errors.confirmPassword ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                    }`}
                  />
                </div>
                {errors.confirmPassword && <p className="text-red-500 text-xs mt-1">{errors.confirmPassword}</p>}
              </div>
            </div>
          )}

          {/* Step 2: Business Details */}
          {currentStep === 2 && !isCreating && !creationComplete && (
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                  Business Details
                </h2>
                <p className="text-gray-600 dark:text-gray-400">
                  Set up your business information
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Business Name *
                </label>
                <div className="relative">
                  <Building2 size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                  <input
                    type="text"
                    value={formData.business_name}
                    onChange={(e) => {
                      const name = e.target.value;
                      const subdomain = name.toLowerCase().replace(/[^a-z0-9-]/g, '').substring(0, 20);
                      setFormData({ ...formData, business_name: name, subdomain });
                    }}
                    className={`w-full pl-10 pr-4 py-3 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
                      errors.business_name ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                    }`}
                  />
                </div>
                {errors.business_name && <p className="text-red-500 text-xs mt-1">{errors.business_name}</p>}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Subdomain *
                </label>
                <div className="flex items-center">
                  <input
                    type="text"
                    value={formData.subdomain}
                    onChange={(e) => setFormData({ ...formData, subdomain: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })}
                    className={`flex-1 px-4 py-3 border rounded-l-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white ${
                      errors.subdomain ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                    }`}
                    placeholder="mybusiness"
                  />
                  <span className="px-4 py-3 bg-gray-100 dark:bg-gray-600 border border-l-0 border-gray-300 dark:border-gray-600 rounded-r-lg text-gray-500 dark:text-gray-400">
                    .{getBaseDomain()}
                  </span>
                </div>
                {errors.subdomain && <p className="text-red-500 text-xs mt-1">{errors.subdomain}</p>}
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  This will be your business URL: {formData.subdomain || 'your-business'}.{getBaseDomain()}
                </p>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Contact Email
                  </label>
                  <input
                    type="email"
                    value={formData.contact_email}
                    onChange={(e) => setFormData({ ...formData, contact_email: e.target.value })}
                    className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Phone (Optional)
                  </label>
                  <input
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Payment Setup (conditional) */}
          {currentStep === 3 && invitation.permissions?.can_accept_payments && !isCreating && !creationComplete && (
            <div className="space-y-6">
              <div>
                <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                  Payment Setup
                </h2>
                <p className="text-gray-600 dark:text-gray-400">
                  Connect Stripe to accept payments (optional - you can do this later)
                </p>
              </div>

              <div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-12 text-center">
                <CreditCard size={48} className="mx-auto text-gray-400 mb-4" />
                <p className="text-gray-600 dark:text-gray-400 mb-4">
                  Stripe Connect onboarding would go here
                </p>
                <button className="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">
                  Connect Stripe
                </button>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-4">
                  You can skip this and set it up later in settings
                </p>
              </div>
            </div>
          )}

          {/* Creating Business - Animated Loading */}
          {isCreating && (
            <div className="space-y-8 py-4">
              <div className="text-center">
                <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                  Creating Your Business
                </h2>
                <p className="text-gray-600 dark:text-gray-400">
                  This typically takes 45-90 seconds. Please don't close this page.
                </p>
              </div>

              <div className="space-y-3">
                {LOADING_STEPS.map((step, index) => {
                  const StepIcon = step.icon;
                  const isComplete = index < loadingStepIndex;
                  const isCurrent = index === loadingStepIndex;

                  return (
                    <div
                      key={step.id}
                      className={`flex items-center gap-4 p-3 rounded-lg transition-all duration-300 ${
                        isComplete
                          ? 'bg-green-50 dark:bg-green-900/20'
                          : isCurrent
                          ? 'bg-indigo-50 dark:bg-indigo-900/20'
                          : 'bg-gray-50 dark:bg-gray-700/50'
                      }`}
                    >
                      <div
                        className={`w-9 h-9 rounded-full flex items-center justify-center transition-all duration-300 ${
                          isComplete
                            ? 'bg-green-500 text-white'
                            : isCurrent
                            ? 'bg-indigo-500 text-white animate-pulse'
                            : 'bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400'
                        }`}
                      >
                        {isComplete ? (
                          <CheckCircle size={18} />
                        ) : isCurrent ? (
                          <Loader size={18} className="animate-spin" />
                        ) : (
                          <StepIcon size={18} />
                        )}
                      </div>
                      <div className="flex-1">
                        <p
                          className={`font-medium text-sm transition-colors duration-300 ${
                            isComplete
                              ? 'text-green-700 dark:text-green-400'
                              : isCurrent
                              ? 'text-indigo-700 dark:text-indigo-400'
                              : 'text-gray-500 dark:text-gray-400'
                          }`}
                        >
                          {step.label}
                          {isComplete && ' ✓'}
                        </p>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Progress section with time */}
              <div className="space-y-2">
                <div className="flex justify-between text-sm text-gray-500 dark:text-gray-400">
                  <span>
                    {loadingStepIndex < LOADING_STEPS.length - 1
                      ? `Step ${loadingStepIndex + 1} of ${LOADING_STEPS.length}`
                      : 'Finalizing...'}
                  </span>
                  <span className="tabular-nums">
                    {Math.floor(elapsedSeconds / 60)}:{(elapsedSeconds % 60).toString().padStart(2, '0')} elapsed
                  </span>
                </div>

                {/* Progress bar - doesn't go to 100% until actually done */}
                <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden">
                  <div
                    className={`h-2 rounded-full transition-all duration-500 ease-out ${
                      loadingStepIndex >= LOADING_STEPS.length - 1
                        ? 'bg-indigo-400 animate-pulse'
                        : 'bg-indigo-600'
                    }`}
                    style={{
                      // Cap at 90% until we're actually complete
                      width: loadingStepIndex >= LOADING_STEPS.length
                        ? '100%'
                        : `${Math.min(90, ((loadingStepIndex + 1) / LOADING_STEPS.length) * 100)}%`,
                    }}
                  />
                </div>

                {/* Show extra message when on final step */}
                {loadingStepIndex >= LOADING_STEPS.length - 1 && (
                  <p className="text-xs text-center text-gray-500 dark:text-gray-400 animate-pulse">
                    Almost there! Setting up your database tables...
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Complete */}
          {creationComplete && (
            <div className="space-y-6 text-center">
              <div className="w-20 h-20 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto">
                <CheckCircle size={48} className="text-green-600 dark:text-green-400" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                  All Set!
                </h2>
                <p className="text-gray-600 dark:text-gray-400">
                  Your business <strong>{formData.business_name}</strong> has been created successfully.
                </p>
              </div>

              <div className="bg-indigo-50 dark:bg-indigo-900/20 rounded-lg p-6">
                <h3 className="font-semibold text-gray-900 dark:text-white mb-2">What's Next?</h3>
                <ul className="text-left space-y-2 text-sm text-gray-600 dark:text-gray-400">
                  <li>✓ Your account has been created</li>
                  <li>✓ Business subdomain: {formData.subdomain}.{getBaseDomain()}</li>
                  <li>✓ You can now log in and start using SmoothSchedule</li>
                </ul>
              </div>

              <button
                onClick={() => {
                  // Redirect to login on the business subdomain
                  window.location.href = buildSubdomainUrl(formData.subdomain, '/login');
                }}
                className="px-8 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium"
              >
                Go to Login
              </button>
            </div>
          )}

          {/* Navigation Buttons */}
          {currentStep < totalSteps && !isCreating && !creationComplete && (
            <div className="flex items-center justify-between mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={handleBack}
                disabled={currentStep === 1}
                className="flex items-center gap-2 px-6 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <ArrowLeft size={18} />
                Back
              </button>

              <button
                onClick={currentStep === 2 && !invitation.permissions?.can_accept_payments ? handleSubmit : handleNext}
                disabled={acceptInvitationMutation.isPending}
                className="flex items-center gap-2 px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {currentStep === 2 && !invitation.permissions?.can_accept_payments ? 'Create Business' : 'Continue'}
                <ArrowRight size={18} />
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default TenantOnboardPage;
