import React, { useState } from "react";
import { usePage } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useCheckoutWizard } from "../WizardContext";
import LoginForm, { AuthUserPayload } from "../../auth/LoginForm";
import RegisterForm, { RegisterSuccessPayload } from "../../auth/RegisterForm";

interface AuthStepProps {
  privacyHtml: string;
}

export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
  const page = usePage<{ locale?: string }>();
  const locale = page.props.locale ?? "de";
  const { isAuthenticated, authUser, markAuthenticated, nextStep, selectedPackage } = useCheckoutWizard();
  const [mode, setMode] = useState<'login' | 'register'>('register');

  const handleLoginSuccess = (payload: AuthUserPayload | null) => {
    if (!payload) {
      return;
    }

    markAuthenticated({
      id: payload.id ?? 0,
      email: payload.email ?? "",
      name: payload.name ?? undefined,
      pending_purchase: Boolean(payload.pending_purchase),
    });
    nextStep();
  };

  const handleRegisterSuccess = (result: RegisterSuccessPayload) => {
    const nextUser = result?.user ?? null;
    if (nextUser) {
      markAuthenticated({
        id: nextUser.id ?? 0,
        email: nextUser.email ?? "",
        name: nextUser.name ?? undefined,
        pending_purchase: Boolean(result?.pending_purchase ?? nextUser.pending_purchase),
      });
    }

    nextStep();
  };

  if (isAuthenticated && authUser) {
    return (
      <div className="space-y-6">
        <Alert>
          <AlertTitle>Bereits eingeloggt</AlertTitle>
          <AlertDescription>
            {authUser.email ? `Sie sind als ${authUser.email} angemeldet.` : "Sie sind bereits angemeldet."}
          </AlertDescription>
        </Alert>
        <div className="flex justify-end">
          <Button size="lg" onClick={nextStep}>
            Weiter zur Zahlung
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center gap-2">
        <Button
          variant={mode === 'register' ? 'default' : 'outline'}
          onClick={() => setMode('register')}
        >
          Registrieren
        </Button>
        <Button
          variant={mode === 'login' ? 'default' : 'outline'}
          onClick={() => setMode('login')}
        >
          Anmelden
        </Button>
        <span className="text-xs text-muted-foreground">
          Google Login folgt im Komfort-Delta.
        </span>
      </div>

      <div className="rounded-lg border bg-card p-6 shadow-sm">
        {mode === 'register' ? (
          <RegisterForm
            packageId={selectedPackage.id}
            privacyHtml={privacyHtml}
            locale={locale}
            onSuccess={handleRegisterSuccess}
          />
        ) : (
          <LoginForm
            locale={locale}
            onSuccess={handleLoginSuccess}
          />
        )}
      </div>
    </div>
  );
};
