'use client';

import { useState, useEffect, useRef, Suspense } from 'react';
import { useAuth } from '@/components/AuthContext';
import { useSearchParams } from 'next/navigation';
import { goToAdminLogin } from '@/lib/roles';

/**
 * Next /login is SSO handoff only (from Filament "Buka Kasir").
 * Manual login always happens at Filament: http://localhost:8000/app/login
 */
function LoginContent() {
  const { ssoLogin, loading: authLoading } = useAuth();
  const [error, setError] = useState('');
  const [ssoLoading, setSsoLoading] = useState(false);
  const lastCalledToken = useRef<string | null>(null);
  const redirectedRef = useRef(false);

  const searchParams = useSearchParams();
  // Capture token once — do not rely on URL after cleanup
  const ssoTokenFromUrl = searchParams.get('sso_token');
  const tokenRef = useRef<string | null>(ssoTokenFromUrl);

  useEffect(() => {
    if (ssoTokenFromUrl) {
      tokenRef.current = ssoTokenFromUrl;
      try {
        sessionStorage.setItem('lasmini_sso_pending', '1');
      } catch {
        /* ignore */
      }
    }
  }, [ssoTokenFromUrl]);

  // Immediate bounce to Filament if no SSO — do NOT wait for /auth/me (proxy can hang on cPanel)
  useEffect(() => {
    const token = tokenRef.current || ssoTokenFromUrl;

    if (!token) {
      if (!redirectedRef.current) {
        redirectedRef.current = true;
        goToAdminLogin();
      }
      return;
    }

    // SSO: wait until AuthProvider finished first paint, then exchange token
    if (authLoading) return;
    if (lastCalledToken.current === token) return;
    lastCalledToken.current = token;
    void handleSsoLogin(token);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authLoading, ssoTokenFromUrl]);

  const handleSsoLogin = async (token: string) => {
    setSsoLoading(true);
    setError('');

    try {
      try {
        sessionStorage.setItem('lasmini_sso_pending', '1');
      } catch {
        /* ignore */
      }

      // Strip token from URL AFTER we captured it (anti replay) — keep sso_pending flag
      if (typeof window !== 'undefined') {
        const url = new URL(window.location.href);
        if (url.searchParams.has('sso_token')) {
          url.searchParams.delete('sso_token');
          window.history.replaceState({}, '', url.pathname + url.search);
        }
      }

      await ssoLogin(token);
      // ssoLogin hard-navigates on success
    } catch (err: unknown) {
      try {
        sessionStorage.removeItem('lasmini_sso_pending');
      } catch {
        /* ignore */
      }
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosErr = err as { response?: { data?: { message?: string } } };
        setError(axiosErr.response?.data?.message || 'Login otomatis gagal.');
      } else if (err instanceof Error && err.message) {
        setError(err.message);
      } else {
        setError('Gagal melakukan login otomatis.');
      }
      // After SSO failure, send user to Filament login
      if (!redirectedRef.current) {
        redirectedRef.current = true;
        setTimeout(() => goToAdminLogin(), 1500);
      }
    } finally {
      setSsoLoading(false);
    }
  };

  const hasSso = !!(tokenRef.current || ssoTokenFromUrl);

  return (
    <div className="flex h-[100dvh] w-full items-center justify-center bg-slate-50">
      <div className="flex flex-col items-center gap-3 px-6 text-center max-w-sm">
        {!error ? (
          <div className="h-10 w-10 animate-spin rounded-full border-3 border-blue-100 border-t-[#005BFF]" />
        ) : null}
        <p className="text-sm font-semibold text-[#005BFF]">
          {ssoLoading
            ? 'Memproses login otomatis ke kasir...'
            : error
              ? 'Login otomatis gagal'
              : hasSso
                ? 'Memuat SSO...'
                : 'Mengalihkan ke halaman login...'}
        </p>
        <p className="text-xs text-slate-500">
          Atau buka manual:{' '}
          <a
            href="https://lasmini.msr27.my.id/app/login"
            className="font-semibold text-blue-700 underline"
          >
            lasmini.msr27.my.id/app/login
          </a>
        </p>
        <button
          type="button"
          onClick={() => goToAdminLogin()}
          className="mt-1 inline-flex items-center justify-center rounded-xl bg-blue-900 px-4 py-2.5 text-sm font-semibold text-white hover:bg-blue-800 cursor-pointer"
        >
          Buka halaman login
        </button>
        {error ? <p className="text-xs text-red-600">{error}</p> : null}
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <div className="flex h-[100dvh] w-full items-center justify-center bg-slate-50">
          <div className="flex flex-col items-center gap-3">
            <div className="h-10 w-10 animate-spin rounded-full border-3 border-blue-100 border-t-[#005BFF]" />
            <p className="text-sm font-semibold text-[#005BFF]">Memuat...</p>
          </div>
        </div>
      }
    >
      <LoginContent />
    </Suspense>
  );
}
