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

const LOCAL_URL = 'http://127.0.0.1:3000';
const SERVER_URL_KEY = 'serverUrl';
const BIOMETRIC_KEY = 'biometricEnabled';

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: SERVER_URL_KEY }).then(async ({ value }) => {
      if (value === 'local') {
        setStage('local');
        return;
      }
      if (value) {
        setServerUrl(value);
        const { value: biometricEnabled } = await Preferences.get({ key: BIOMETRIC_KEY });
        setStage(biometricEnabled === 'true' ? 'biometric-lock' : 'redirecting');
        return;
      }
      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: SERVER_URL_KEY, value: 'local' });
    setStage('local');
  }

  async function handleLoginSuccess() {
    await Preferences.set({ key: SERVER_URL_KEY, 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: BIOMETRIC_KEY, value: enabled ? 'true' : 'false' });
    setStage('redirecting');
  }

  async function handleBiometricFallback() {
    await Preferences.set({ key: BIOMETRIC_KEY, 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>
      );
  }
}
