import { useEffect, useState } from 'react';
import { Preferences } from '@capacitor/preferences';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';
import { LOCAL_URL, PREF_SERVER_URL, PREF_BIOMETRIC, LOCAL_MODE_SENTINEL } from './config';
import SetupScreen from './SetupScreen';
import LoadingScreen from './LoadingScreen';
import LoginScreen from './LoginScreen';
import BiometricSetup from './BiometricSetup';
import BiometricLock from './BiometricLock';

type Stage =
  | 'checking'
  | 'setup'
  | 'login'
  | 'biometric-setup'
  | 'biometric-lock'
  | 'local'
  | 'redirecting';

export default function App() {
  const [stage, setStage] = useState<Stage>('checking');
  const [serverUrl, setServerUrl] = useState('');

  useEffect(() => {
    Preferences.get({ key: PREF_SERVER_URL })
      .then(async ({ value }) => {
        if (value === LOCAL_MODE_SENTINEL) {
          setStage('local');
          return;
        }
        if (value) {
          setServerUrl(value);
          const { value: biometricEnabled } = await Preferences.get({ key: PREF_BIOMETRIC });
          setStage(biometricEnabled === 'true' ? 'biometric-lock' : 'redirecting');
          return;
        }
        setStage('setup');
      })
      // A failed preferences read must not leave us stuck on the spinner —
      // fall back to first-run setup so the user can (re)connect.
      .catch(() => setStage('setup'));
  }, []);

  useEffect(() => {
    if (stage === 'redirecting') {
      window.location.replace(serverUrl);
    }
  }, [stage, serverUrl]);

  function handleConnect(url: string) {
    setServerUrl(url);
    setStage('login');
  }

  async function handleLocalMode() {
    await Preferences.set({ key: PREF_SERVER_URL, value: LOCAL_MODE_SENTINEL });
    setStage('local');
  }

  async function handleLoginSuccess() {
    await Preferences.set({ key: PREF_SERVER_URL, value: serverUrl });
    try {
      const { isAvailable } = await BiometricAuth.checkBiometry();
      setStage(isAvailable ? 'biometric-setup' : 'redirecting');
    } catch {
      setStage('redirecting');
    }
  }

  async function handleBiometricSetupDone(enabled: boolean) {
    await Preferences.set({ key: PREF_BIOMETRIC, value: enabled ? 'true' : 'false' });
    setStage('redirecting');
  }

  async function handleBiometricFallback() {
    await Preferences.set({ key: PREF_BIOMETRIC, value: 'false' });
    setStage('login');
  }

  switch (stage) {
    case 'local':
      return <LoadingScreen onReady={() => window.location.replace(LOCAL_URL)} />;

    case 'setup':
      return <SetupScreen onConnect={handleConnect} onLocalMode={handleLocalMode} />;

    case 'login':
      return (
        <LoginScreen
          serverUrl={serverUrl}
          onSuccess={handleLoginSuccess}
          onBack={() => setStage('setup')}
        />
      );

    case 'biometric-setup':
      return <BiometricSetup onDone={handleBiometricSetupDone} />;

    case 'biometric-lock':
      return <BiometricLock onUnlocked={() => setStage('redirecting')} onFallback={handleBiometricFallback} />;

    default:
      // 'checking' / 'redirecting' — brief blank while we check preferences
      // or hand off to the WebView.
      return (
        <div style={{ background: '#09090b', height: '100dvh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div className="spinner" />
        </div>
      );
  }
}
