'use client';

import { useEffect } from 'react';
import { useSearchParams } from 'next/navigation';

import { startKeycloakLogin } from '@/lib/keycloak-oidc';
import { pickAppText } from '@/lib/i18n/core';
import { useAppI18n } from '@/lib/i18n/provider';

export default function LoginRedirectPage() {
  const { locale } = useAppI18n();
  const searchParams = useSearchParams();
  const loggedOut = searchParams?.get('logged_out') === '1';

  useEffect(() => {
    if (loggedOut) return;
    const nextPath = searchParams?.get('next') || '/';
    void startKeycloakLogin(nextPath);
  }, [loggedOut, searchParams]);

  if (loggedOut) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-4 px-4 text-center">
        <div className="text-sm text-muted-foreground">
          {pickAppText(locale, '你已退出登录。', 'You have signed out.')}
        </div>
        <button
          type="button"
          className="rounded-full bg-primary px-5 py-2 text-sm font-semibold text-primary-foreground"
          onClick={() => {
            const nextPath = searchParams?.get('next') || '/';
            void startKeycloakLogin(nextPath);
          }}
        >
          {pickAppText(locale, '重新登录', 'Sign in again')}
        </button>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <div className="text-sm text-muted-foreground">
        {pickAppText(locale, '正在跳转到 Keycloak 登录...', 'Redirecting to Keycloak sign-in...')}
      </div>
    </div>
  );
}
