import React, { useState } from 'react';
import { WelcomePage } from './components/WelcomePage';
import { LoginForm } from './components/auth/LoginForm';
import { RegistrationForm } from './components/RegistrationForm';
import { AvatarSelector } from './components/AvatarSelector';
import { ThemeSelector } from './components/ThemeSelector';
import { StoryViewer } from './components/StoryViewer';
import { StoryLibrary } from './components/library/StoryLibrary';
import { AuthUser, SavedStory } from './types/auth';
import { User, Theme } from './types';
import { AuthProvider } from './contexts/AuthContext'
import { useNavigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

type AppStep = 
  | 'welcome'
  | 'login'
  | 'register'
  | 'avatar'
  | 'theme'
  | 'story'
  | 'library';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutos
      gcTime: 1000 * 60 * 30,   // 30 minutos (antes era cacheTime)
      refetchOnWindowFocus: false,
    },
  },
})

export function App() {
  const navigate = useNavigate();
  const [step, setStep] = useState<AppStep>('welcome');
  const [user, setUser] = useState<User | null>(null);
  const [authUser, setAuthUser] = useState<AuthUser | null>(null);
  const [selectedTheme, setSelectedTheme] = useState<Theme | null>(null);
  const [savedStories] = useState<SavedStory[]>([
    {
      id: '1',
      title: 'A Aventura na Floresta Amazônica',
      theme: 'Natureza e Meio Ambiente',
      createdAt: '2024-03-15T10:00:00Z',
      lastReadPage: 2,
    },
  ]);

  const handleLogin = async (credentials: { email: string; password: string }) => {
    try {
      // In production: Implement actual authentication
      setAuthUser({ id: '1', email: credentials.email, name: 'Usuário' });
      // Redirecionar para o dashboard ao invés de library
      navigate('/dashboard');
    } catch (err) {
      console.error('Erro ao fazer login:', err);
    }
  };

  const handleRegistrationComplete = (userData: User) => {
    setUser(userData);
    setStep('avatar');
  };

  const handleAvatarComplete = (avatarId: string) => {
    if (user) {
      setUser({ ...user, avatarId });
      setStep('theme');
    }
  };

  const handleThemeSelect = (theme: Theme) => {
    setSelectedTheme(theme);
    setStep('story');
  };

  const handleStorySelect = (storyId: string) => {
    // In production: Load the selected story
    const story = savedStories.find(s => s.id === storyId);
    if (story) {
      // Navigate to the story viewer
      setStep('story');
    }
  };

  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <div className="min-h-screen bg-gradient-to-b from-purple-100 to-blue-100">
          {step === 'welcome' && (
            <WelcomePage
              onLoginClick={() => setStep('login')}
              onRegisterClick={() => setStep('register')}
            />
          )}
          {step === 'login' && (
            <div className="min-h-screen flex items-center justify-center p-6">
              <LoginForm
                userType="school"
                onLogin={handleLogin}
                onRegisterClick={() => setStep('register')}
              />
            </div>
          )}
          {step === 'register' && (
            <RegistrationForm 
              userType="school"
              onComplete={handleRegistrationComplete} 
            />
          )}
          {step === 'avatar' && user && (
            <AvatarSelector user={user} onComplete={handleAvatarComplete} />
          )}
          {step === 'theme' && <ThemeSelector onSelect={handleThemeSelect} />}
          {step === 'story' && user && selectedTheme && (
            <StoryViewer theme={selectedTheme} user={user} />
          )}
          {step === 'library' && authUser && (
            <StoryLibrary
              stories={savedStories}
              onStorySelect={handleStorySelect}
            />
          )}
        </div>
      </AuthProvider>
    </QueryClientProvider>
  );
}