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";
import { useTranslation } from 'react-i18next';

interface AuthStepProps {
  privacyHtml: string;
}

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

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

    setAuthUser({
      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) {
      setAuthUser({
        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>{t('checkout.auth_step.already_logged_in_title')}</AlertTitle>
          <AlertDescription>
            {t('checkout.auth_step.already_logged_in_desc', { email: authUser?.email || '' })}
          </AlertDescription>
        </Alert>
        <div className="flex justify-end">
          <Button size="lg" onClick={nextStep}>
            {t('checkout.auth_step.next_to_payment')}
          </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')}
        >
          {t('checkout.auth_step.switch_to_register')}
        </Button>
        <Button
          variant={mode === 'login' ? 'default' : 'outline'}
          onClick={() => setMode('login')}
        >
          {t('checkout.auth_step.switch_to_login')}
        </Button>
        <span className="text-xs text-muted-foreground">
          {t('checkout.auth_step.google_coming_soon')}
        </span>
      </div>

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