import React, { useState, useEffect } from 'react';
import { Head, useForm, usePage, router } from '@inertiajs/react';
import { useTranslation } from 'react-i18next';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { Steps } from '@/components/ui/steps'; // Assume Shadcn Steps component; add if needed via shadcn
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Loader2 } from 'lucide-react';
import MarketingLayout from '@/layouts/marketing/MarketingLayout';
import RegisterForm from '../auth/RegisterForm'; // Extract Register form to separate component
import LoginForm from '../auth/LoginForm'; // Extract Login form
import PaymentForm from './PaymentForm'; // New component for Stripe payment
import SuccessStep from './SuccessStep'; // New component for success

interface Package {
  id: number;
  name: string;
  description: string;
  price: number;
  features: string[];
  // Add other fields as needed
}

interface PurchaseWizardProps {
  package: Package;
  stripePublishableKey: string;
  privacyHtml: string;
}

const steps = [
  { id: 'package', title: 'Paket auswählen', description: 'Bestätigen Sie Ihr gewähltes Paket' },
  { id: 'auth', title: 'Anmelden oder Registrieren', description: 'Erstellen oder melden Sie sich an' },
  { id: 'payment', title: 'Zahlung', description: 'Sichern Sie Ihr Paket ab' },
  { id: 'success', title: 'Erfolg', description: 'Willkommen!' },
];

export default function PurchaseWizard({ package: initialPackage, stripePublishableKey, privacyHtml }: PurchaseWizardProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [authType, setAuthType] = useState<'register' | 'login'>('register'); // Toggle for auth step
  const [wizardData, setWizardData] = useState({ package: initialPackage, user: null });
  const { t } = useTranslation(['marketing', 'auth']);
  const { props } = usePage();
  const { auth } = props as any;

  useEffect(() => {
    if (auth.user) {
      setIsAuthenticated(true);
      setCurrentStep(2); // Skip to payment if already logged in
    }
  }, [auth]);

  const stripePromise = loadStripe(stripePublishableKey);

  const nextStep = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep((prev) => prev + 1);
    }
  };

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

  const handleAuthSuccess = (userData: any) => {
    setWizardData((prev) => ({ ...prev, user: userData }));
    setIsAuthenticated(true);
    nextStep(); // Proceed to payment or success
  };

  const handlePaymentSuccess = () => {
    // Call API to assign package
    router.post('/api/purchase/complete', { package_id: initialPackage.id }, {
      onSuccess: () => nextStep(),
    });
  };

  const renderStepContent = () => {
    switch (steps[currentStep].id) {
      case 'package':
        return (
          <Card>
            <CardHeader>
              <CardTitle>{initialPackage.name}</CardTitle>
              <CardDescription>{initialPackage.description}</CardDescription>
            </CardHeader>
            <CardContent>
              <p>Preis: {initialPackage.price === 0 ? 'Kostenlos' : `${initialPackage.price} €`}</p>
              <ul>
                {initialPackage.features.map((feature, index) => (
                  <li key={index}>{feature}</li>
                ))}
              </ul>
              <Button onClick={nextStep} className="w-full mt-4">Weiter</Button>
            </CardContent>
          </Card>
        );
      case 'auth':
        return (
          <div>
            <div className="flex justify-center mb-4">
              <Button
                variant={authType === 'register' ? 'default' : 'outline'}
                onClick={() => setAuthType('register')}
              >
                Registrieren
              </Button>
              <Button
                variant={authType === 'login' ? 'default' : 'outline'}
                onClick={() => setAuthType('login')}
                className="ml-2"
              >
                Anmelden
              </Button>
            </div>
            {authType === 'register' ? (
              <RegisterForm onSuccess={handleAuthSuccess} packageId={initialPackage.id} privacyHtml={privacyHtml} />
            ) : (
              <LoginForm onSuccess={handleAuthSuccess} />
            )}
          </div>
        );
      case 'payment':
        if (initialPackage.price === 0) {
          // Skip for free, assign directly
          router.post('/api/purchase/free', { package_id: initialPackage.id });
          return <div>Free package assigned! Redirecting...</div>;
        }
        return (
          <Elements stripe={stripePromise}>
            <PaymentForm packageId={initialPackage.id} onSuccess={handlePaymentSuccess} />
          </Elements>
        );
      case 'success':
        return <SuccessStep package={initialPackage} />;
      default:
        return null;
    }
  };

  return (
    <MarketingLayout title="Kauf-Wizard">
      <Head title="Kauf-Wizard" />
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="max-w-2xl mx-auto px-4">
          <Progress value={(currentStep / (steps.length - 1)) * 100} className="mb-6" />
          <Steps steps={steps} currentStep={currentStep} />
          {renderStepContent()}
          {currentStep > 0 && currentStep < 3 && (
            <div className="flex justify-between mt-6">
              <Button variant="outline" onClick={prevStep}>Zurück</Button>
              {currentStep < 3 && <Button onClick={nextStep}>Weiter</Button>}
            </div>
          )}
        </div>
      </div>
    </MarketingLayout>
  );
}