import { useState, useEffect } from 'react';
import Layout, { type Panel } from './components/Layout';
import Subscriptions from './components/Subscriptions';
import StaticNodes from './components/StaticNodes';
import NodeSelector from './components/NodeSelector';
import Rules from './components/Rules';
import Output from './components/Output';
import { auth, setToken } from './api';

function LoginPage({ onLogin }: { onLogin: () => void }) {
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isSetup, setIsSetup] = useState(false);

  useEffect(() => {
    auth.status().then(data => {
      setIsSetup(data.hasPassword);
    });
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!password) return;
    try {
      await auth.login(password);
      setToken(password);
      onLogin();
    } catch {
      setError('密码错误');
    }
  };

  return (
    <div style={{
      height: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--bg-primary)',
    }}>
      <div style={{
        background: 'var(--bg-panel)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--radius)',
        padding: 40,
        width: 360,
        textAlign: 'center',
      }}>
        <div style={{
          fontFamily: 'var(--font-mono)',
          fontSize: 20,
          fontWeight: 700,
          color: 'var(--accent)',
          marginBottom: 8,
          letterSpacing: '0.1em',
        }}>
          Sub Router
        </div>
        <div style={{
          fontSize: 12,
          color: 'var(--text-secondary)',
          marginBottom: 24,
        }}>
          {isSetup ? '输入密码以访问管理面板' : '设置管理密码'}
        </div>
        <form onSubmit={handleSubmit}>
          <input
            type="password"
            placeholder={isSetup ? '密码' : '设置新密码'}
            value={password}
            onChange={e => setPassword(e.target.value)}
            style={{
              width: '100%',
              marginBottom: 12,
              textAlign: 'center',
              fontSize: 14,
              padding: 10,
            }}
            autoFocus
          />
          {error && (
            <div style={{ color: 'var(--danger)', fontSize: 12, marginBottom: 12 }}>
              {error}
            </div>
          )}
          <button className="primary" type="submit" style={{ width: '100%' }}>
            {isSetup ? '登录' : '设置密码'}
          </button>
        </form>
      </div>
    </div>
  );
}

export default function App() {
  const [activePanel, setActivePanel] = useState<Panel>('subscriptions');
  const [authenticated, setAuthenticated] = useState(false);
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    // Check if auth is needed and if we have a valid token
    auth.status().then(data => {
      if (!data.hasPassword) {
        // No password set yet — show login to set one
        setChecking(false);
        return;
      }
      // Try existing token
      const token = sessionStorage.getItem('sub-router-token');
      if (token) {
        setToken(token);
        // Verify by calling stats
        fetch('/api/stats', {
          headers: { Authorization: `Bearer ${token}` },
        }).then(res => {
          if (res.ok) setAuthenticated(true);
          setChecking(false);
        }).catch(() => setChecking(false));
      } else {
        setChecking(false);
      }
    }).catch(() => setChecking(false));
  }, []);

  if (checking) {
    return (
      <div style={{
        height: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'var(--text-muted)',
        fontFamily: 'var(--font-mono)',
      }}>
        Loading...
      </div>
    );
  }

  if (!authenticated) {
    return <LoginPage onLogin={() => setAuthenticated(true)} />;
  }

  const panels: Record<Panel, React.ReactNode> = {
    subscriptions: <Subscriptions />,
    'static-nodes': <StaticNodes />,
    'node-selector': <NodeSelector />,
    rules: <Rules />,
    output: <Output />,
  };

  return (
    <Layout activePanel={activePanel} onPanelChange={setActivePanel}>
      {panels[activePanel]}
    </Layout>
  );
}
