'use client';

import { Button } from '@/components/ui/button';
import { initializeAuthenticatedApp } from '@/services/initializer.service';
import { useAppStore } from '@/store/app.store';
import { useAuthStore } from '@/store/auth.store';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';

export default function AppInitializer({ children }: { children: ReactNode }) {
  const accessToken = useAuthStore((state) => state.accessToken);
  const user = useAppStore((state) => state.user);
  const loadStatus = useAppStore((state) => state.loadStatus);
  const setLoading = useAppStore((state) => state.setLoading);
  const setLoaded = useAppStore((state) => state.setLoaded);
  const setLoadError = useAppStore((state) => state.setLoadError);
  const [retryAttempt, setRetryAttempt] = useState(0);

  useEffect(() => {
    let isActive = true;

    const initialize = async () => {
      if (!accessToken || user) {
        setLoaded();
        return;
      }

      setLoading();

      try {
        await initializeAuthenticatedApp();
      } catch {
        if (isActive) {
          setLoadError();
        }
      }
    };

    initialize();

    return () => {
      isActive = false;
    };
  }, [accessToken, retryAttempt, setLoaded, setLoadError, setLoading, user]);

  if (accessToken && !user && loadStatus === 'error') {
    return (
      <main className="flex min-h-screen items-center justify-center bg-background px-6">
        <div
          className="flex max-w-md flex-col items-center gap-4 text-center"
          role="alert"
        >
          <div className="space-y-2">
            <h1 className="text-xl font-semibold">Unable to load workspace</h1>
            <p className="text-sm text-muted-foreground">
              We could not load your account details. Your session has been
              kept, so you can safely try again.
            </p>
          </div>
          <Button
            type="button"
            onClick={() => setRetryAttempt((value) => value + 1)}
          >
            Try again
          </Button>
        </div>
      </main>
    );
  }

  return children;
}
