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 { OAuthProfilePrefill } 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 { LoaderCircle } from "lucide-react";

interface AuthStepProps {
  privacyHtml: string;
  prefill?: OAuthProfilePrefill;
  onClearPrefill?: () => void;
}

type OAuthAuthFlash = {
  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>
);

const FacebookIcon: React.FC<{ className?: string }> = ({ className }) => (
  <svg
    className={className}
    viewBox="0 0 24 24"
    aria-hidden="true"
    focusable="false"
  >
    <path
      fill="#1877F2"
      d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.014 1.792-4.68 4.533-4.68 1.312 0 2.686.236 2.686.236v2.96h-1.513c-1.49 0-1.954.93-1.954 1.887v2.264h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073Z"
    />
  </svg>
);

export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, prefill, onClearPrefill }) => {
  const { t } = useTranslation('marketing');
  const page = usePage<{ locale?: string }>();
  const locale = page.props.locale ?? "de";
  const googleAuth = useMemo<OAuthAuthFlash>(() => {
    const props = page.props as { googleAuth?: OAuthAuthFlash };
    return props.googleAuth ?? {};
  }, [page.props]);
  const facebookAuth = useMemo<OAuthAuthFlash>(() => {
    const props = page.props as { facebookAuth?: OAuthAuthFlash };
    return props.facebookAuth ?? {};
  }, [page.props]);
  const { isAuthenticated, authUser, setAuthUser, nextStep, selectedPackage } = useCheckoutWizard();
  const [mode, setMode] = useState<'login' | 'register'>('register');
  const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
  const [isRedirectingToFacebook, setIsRedirectingToFacebook] = useState(false);
  const showOauthControls = mode === 'register';
  const authErrorTitle = facebookAuth?.error
    ? t('checkout.auth_step.facebook_error_title')
    : t('checkout.auth_step.google_error_title');

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

  useEffect(() => {
    if (facebookAuth?.status === 'signin') {
      toast.success(t('checkout.auth_step.facebook_success_toast'));
      onClearPrefill?.();
    }
  }, [facebookAuth?.status, onClearPrefill, t]);

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

  useEffect(() => {
    if (facebookAuth?.error) {
      toast.error(facebookAuth.error);
    }
  }, [facebookAuth?.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),
    });
    onClearPrefill?.();
    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),
      });
    }

    onClearPrefill?.();
    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]);

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

    setIsRedirectingToFacebook(true);
    const params = new URLSearchParams({
      package_id: String(selectedPackage.id),
      locale,
    });
    window.location.href = `/checkout/auth/facebook?${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">
      <div className="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>
          {showOauthControls && (
            <div className="flex flex-1 flex-wrap items-center 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>
              <Button
                variant="outline"
                onClick={handleFacebookLogin}
                disabled={isRedirectingToFacebook}
                className="flex items-center gap-2"
              >
                {isRedirectingToFacebook ? (
                  <LoaderCircle className="h-4 w-4 animate-spin" />
                ) : (
                  <FacebookIcon className="h-4 w-4" />
                )}
                {t('checkout.auth_step.continue_with_facebook')}
              </Button>
            </div>
          )}
        </div>
      </div>

      {(googleAuth?.error || facebookAuth?.error) && (
        <Alert variant="destructive">
          <AlertTitle>{authErrorTitle}</AlertTitle>
          <AlertDescription>{facebookAuth?.error ?? 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={prefill}
              onClearPrefill={onClearPrefill}
            />
          )
        ) : (
          <LoginForm
            locale={locale}
            onSuccess={handleLoginSuccess}
            packageId={selectedPackage?.id ?? null}
          />
        )}
      </div>
    </div>
  );
};
