import { useEffect, useState } from 'react';
import { ActivityIndicator, StyleSheet, Text } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import AuthScreen from './src/AuthScreen';
import MarketplaceApp, { type MarketplaceAction } from './src/MarketplaceApp';
import { ApiError, clearToken, getMe, readToken, saveToken } from './src/api';
import type { User } from './src/types';
import { colors } from './src/theme';

export default function App() {
  const [token, setToken] = useState<string | null>(null);
  const [user, setUser] = useState<User | null>(null);
  const [booting, setBooting] = useState(true);
  const [notice, setNotice] = useState('');
  const [startupError, setStartupError] = useState('');
  const [authIntent, setAuthIntent] = useState<MarketplaceAction | { type: 'login' } | null>(null);
  const [authVisible, setAuthVisible] = useState(false);
  const [initialAction, setInitialAction] = useState<MarketplaceAction | undefined>();
  const [marketplaceNotice, setMarketplaceNotice] = useState('');

  useEffect(() => {
    let active = true;
    async function restoreSession() {
      try {
        const savedToken = await readToken();
        if (!savedToken) {
          return;
        }
        try {
          const response = await getMe(savedToken);
          if (active) {
            setToken(savedToken);
            setUser(response.user);
          }
        } catch (sessionError) {
          if (sessionError instanceof ApiError && sessionError.status === 401) {
            await clearToken();
            if (active) {
              setNotice('Your saved sign-in has expired. Please sign in again.');
            }
          } else {
            throw sessionError;
          }
        }
      } catch (restoreError) {
        if (active) {
          setStartupError(restoreError instanceof Error ? restoreError.message : 'Could not restore your sign-in.');
        }
      } finally {
        if (active) {
          setBooting(false);
        }
      }
    }
    void restoreSession();
    return () => {
      active = false;
    };
  }, []);

  async function authenticate(nextToken: string, nextUser: User) {
    await saveToken(nextToken);
    setStartupError('');
    setNotice('');
    setToken(nextToken);
    setUser(nextUser);
    if (authIntent?.type === 'post' && nextUser.role === 'customer') {
      setInitialAction(authIntent);
      setMarketplaceNotice('');
    } else if (authIntent?.type === 'bid' && nextUser.role === 'contractor') {
      setInitialAction(authIntent);
      setMarketplaceNotice('');
    } else if (authIntent?.type === 'post' || authIntent?.type === 'bid') {
      setInitialAction(undefined);
      setMarketplaceNotice(
        authIntent.type === 'post'
          ? 'Posting jobs requires a customer account.'
          : 'Placing bids requires a contractor account.',
      );
    } else {
      setInitialAction(undefined);
      setMarketplaceNotice('');
    }
    setAuthIntent(null);
    setAuthVisible(false);
  }

  function signedOut() {
    setToken(null);
    setUser(null);
    setNotice('You have signed out.');
  }

  return (
    <SafeAreaProvider>
      <StatusBar style="dark" />
      {booting ? (
        <SafeAreaView style={styles.loading}>
          <ActivityIndicator color={colors.primary} size="large" />
          <Text style={styles.loadingText}>Connecting to JaforLife...</Text>
        </SafeAreaView>
      ) : authVisible ? (
        <AuthScreen
          initialNotice={startupError || notice}
          initialRole={authIntent?.type === 'post' ? 'customer' : authIntent?.type === 'bid' ? 'contractor' : undefined}
          onCancel={() => {
            setAuthVisible(false);
            setAuthIntent(null);
          }}
          onAuthenticated={authenticate}
        />
      ) : (
        <MarketplaceApp
          token={token || undefined}
          user={token ? user || undefined : undefined}
          onSignedOut={signedOut}
          onRequireAuth={(intent) => {
            setAuthIntent(intent);
            setAuthVisible(true);
          }}
          initialAction={initialAction}
          onInitialActionHandled={() => setInitialAction(undefined)}
          initialNotice={marketplaceNotice || notice}
        />
      )}
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  loading: {
    alignItems: 'center',
    backgroundColor: colors.canvas,
    flex: 1,
    justifyContent: 'center',
  },
  loadingText: {
    color: colors.muted,
    fontSize: 14,
    marginTop: 14,
  },
});
