import { OnboardLoginPage } from '@/features/onboard/onboard-login-page';
import { apiClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { acceptStoredPendingInvite, setPendingInvite } from '@/lib/invitations';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { useEffect } from 'react';
import { z } from 'zod';

const inviteSearchSchema = z.object({
  email: z.string().email().optional(),
  inviteToken: z.string().min(1).optional(),
});

function InvitePage() {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuth();
  const search = Route.useSearch();

  useEffect(() => {
    setPendingInvite({
      email: search.email ?? null,
      token: search.inviteToken ?? null,
    });
  }, [search.email, search.inviteToken]);

  useEffect(() => {
    if (!isAuthenticated) {
      return;
    }

    void (async () => {
      await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
      await navigate({ to: '/' });
    })();
  }, [isAuthenticated, navigate]);

  if (isAuthenticated) {
    return (
      <main className="flex min-h-screen w-full items-center justify-center px-3 sm:px-6">
        <p className="text-sm text-muted-foreground">Aceptando invitación...</p>
      </main>
    );
  }

  return <OnboardLoginPage variant="invite" inviteEmail={search.email ?? null} />;
}

export const Route = createFileRoute('/invite')({
  validateSearch: inviteSearchSchema,
  component: InvitePage,
});
