import React, { useCallback, useEffect, useMemo, 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 type { GoogleProfilePrefill } from '../types';
import LoginForm, { AuthUserPayload } from "../../../auth/LoginForm";
import RegisterForm, { RegisterSuccessPayload } from "../../../auth/RegisterForm";
import { Trans, useTranslation } from 'react-i18next';
import toast from 'react-hot-toast';
import { ChevronDown, LoaderCircle } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";

interface AuthStepProps {
  privacyHtml: string;
  googleProfile?: GoogleProfilePrefill;
  onClearGoogleProfile?: () => void;
}

type GoogleAuthFlash = {
  status?: string | null;
  error?: string | null;
};

const GoogleIcon: React.FC<{ className?: string }> = ({ className }) => (
  <svg
    className={className}
    viewBox="0 0 24 24"
    aria-hidden="true"
    focusable="false"
  >
    <path fill="#EA4335" d="M12 11.999v4.8h6.7c-.3 1.7-2 4.9-6.7 4.9-4 0-7.4-3.3-7.4-7.4S8 6 12 6c2.3 0 3.9 1 4.8 1.9l3.3-3.2C18.1 2.6 15.3 1 12 1 5.9 1 1 5.9 1 12s4.9 11 11 11c6.3 0 10.5-4.4 10.5-10.6 0-.7-.1-1.2-.2-1.8H12z" />
  </svg>
);

export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile, onClearGoogleProfile }) => {
  const { t } = useTranslation('marketing');
  const page = usePage<{ locale?: string }>();
  const locale = page.props.locale ?? "de";
  const googleAuth = useMemo<GoogleAuthFlash>(() => {
    const props = page.props as { googleAuth?: GoogleAuthFlash };
    return props.googleAuth ?? {};
  }, [page.props]);
  const { isAuthenticated, authUser, setAuthUser, nextStep, selectedPackage } = useCheckoutWizard();
  const [mode, setMode] = useState<'login' | 'register'>('register');
  const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
  const [showGoogleHelper, setShowGoogleHelper] = useState(false);

  useEffect(() => {
    if (googleAuth?.status === 'signin') {
      toast.success(t('checkout.auth_step.google_success_toast'));
      onClearGoogleProfile?.();
    }
  }, [googleAuth?.status, onClearGoogleProfile, t]);

  useEffect(() => {
    if (googleAuth?.error) {
      toast.error(googleAuth.error);
    }
  }, [googleAuth?.error]);

  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),
    });
    onClearGoogleProfile?.();
    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),
      });
    }

    onClearGoogleProfile?.();
    nextStep();
  };

  const handleGoogleLogin = useCallback(() => {
    if (!selectedPackage) {
      toast.error(t('checkout.auth_step.google_missing_package'));
      return;
    }

    setIsRedirectingToGoogle(true);
    const params = new URLSearchParams({
      package_id: String(selectedPackage.id),
      locale,
    });
    window.location.href = `/checkout/auth/google?${params.toString()}`;
  }, [locale, selectedPackage, t]);

  if (isAuthenticated && authUser) {
    return (
      <div className="space-y-6">
        <Alert className="border-primary/40 bg-primary/5">
          <AlertTitle className="text-xl font-semibold">
            {t('checkout.auth_step.already_logged_in_title')}
          </AlertTitle>
          <AlertDescription className="space-y-2 text-base leading-relaxed">
            <Trans
              t={t}
              i18nKey="checkout.auth_step.already_logged_in_body"
              components={{ strong: <span className="font-semibold" /> }}
              values={{ email: authUser?.email || '' }}
            />
            <p className="text-sm text-muted-foreground">
              {t('checkout.auth_step.already_logged_in_hint')}
            </p>
          </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">
      <Collapsible open={showGoogleHelper} onOpenChange={setShowGoogleHelper} className="w-full space-y-2">
        <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>
          <div className="flex flex-1 justify-start gap-2 sm:flex-none">
            <Button
              variant="outline"
              onClick={handleGoogleLogin}
              disabled={isRedirectingToGoogle}
              className="flex items-center gap-2"
            >
              {isRedirectingToGoogle ? (
                <LoaderCircle className="h-4 w-4 animate-spin" />
              ) : (
                <GoogleIcon className="h-4 w-4" />
              )}
              {t('checkout.auth_step.continue_with_google')}
            </Button>
            <CollapsibleTrigger asChild>
              <button
                type="button"
                className={cn(
                  "inline-flex items-center gap-1 rounded-full border border-muted-foreground/30 px-3 py-1 text-xs font-medium text-muted-foreground transition hover:border-muted-foreground/60 hover:text-foreground",
                  showGoogleHelper && "bg-muted/60 text-foreground"
                )}
              >
                {t('checkout.auth_step.google_helper_badge')}
                <ChevronDown className={cn("h-3 w-3 transition-transform", showGoogleHelper && "rotate-180")} />
              </button>
            </CollapsibleTrigger>
          </div>
        </div>
        <CollapsibleContent>
          <Alert className="border-dashed border-muted/60 bg-muted/20 text-xs sm:text-sm">
            <AlertDescription>{t('checkout.auth_step.google_helper')}</AlertDescription>
          </Alert>
        </CollapsibleContent>
      </Collapsible>

      {googleAuth?.error && (
        <Alert variant="destructive">
          <AlertTitle>{t('checkout.auth_step.google_error_title')}</AlertTitle>
          <AlertDescription>{googleAuth.error}</AlertDescription>
        </Alert>
      )}

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