import React, { useState, useEffect } from 'react';
import {
  ShadeProvider,
  IdentityCard,
  SessionList,
  PrekeyStock,
  RecentActivity,
  ServerStatus,
  FingerprintCompare,
} from '@shade/widgets';
import { Login } from './Login.js';

const STORAGE_KEY = 'shade-dashboard-config';

interface DashboardConfig {
  observerUrl: string;
  token: string;
}

export function App(): React.ReactElement {
  const [config, setConfig] = useState<DashboardConfig | null>(null);

  useEffect(() => {
    // Determine the default observer URL: assume dashboard is served from
    // the same origin as the observer, so the API is at the parent path
    const defaultUrl = window.location.origin + window.location.pathname.replace(/\/dashboard\/?$/, '');

    try {
      const stored = window.localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored) as DashboardConfig;
        if (parsed.observerUrl && parsed.token) {
          setConfig(parsed);
          return;
        }
      }
    } catch {}

    // Show login screen
    setConfig({ observerUrl: defaultUrl, token: '' });
  }, []);

  function handleLogin(observerUrl: string, token: string): void {
    const cfg = { observerUrl, token };
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cfg));
    setConfig(cfg);
  }

  function handleLogout(): void {
    window.localStorage.removeItem(STORAGE_KEY);
    setConfig({ observerUrl: window.location.origin, token: '' });
  }

  if (!config) {
    return <div style={{ padding: 40, textAlign: 'center' }}>Loading…</div>;
  }

  if (!config.token) {
    return <Login defaultUrl={config.observerUrl} onLogin={handleLogin} />;
  }

  return (
    <ShadeProvider observerUrl={config.observerUrl} token={config.token}>
      <DashboardLayout onLogout={handleLogout} />
    </ShadeProvider>
  );
}

function DashboardLayout({ onLogout }: { onLogout: () => void }): React.ReactElement {
  return (
    <div
      style={{
        maxWidth: 1400,
        margin: '0 auto',
        padding: 24,
        display: 'flex',
        flexDirection: 'column',
        gap: 24,
      }}
    >
      <header
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          paddingBottom: 16,
          borderBottom: '1px solid #262626',
        }}
      >
        <div>
          <h1
            style={{
              margin: 0,
              fontSize: 22,
              fontWeight: 600,
              color: '#f7c948',
              letterSpacing: '-0.01em',
            }}
          >
            Shade Observer
          </h1>
          <div style={{ fontSize: 12, color: '#a3a3a3', marginTop: 2 }}>
            Live debugger for your Signal Protocol deployment
          </div>
        </div>
        <button
          onClick={onLogout}
          style={{
            background: 'transparent',
            border: '1px solid #262626',
            color: '#a3a3a3',
            padding: '6px 14px',
            borderRadius: 6,
            cursor: 'pointer',
            fontSize: 12,
            fontFamily: 'inherit',
          }}
        >
          Sign out
        </button>
      </header>

      <IdentityCard />

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'minmax(280px, 1fr) minmax(280px, 1fr) minmax(280px, 1fr)',
          gap: 20,
        }}
      >
        <PrekeyStock />
        <ServerStatus />
        <FingerprintCompare />
      </div>

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 20,
        }}
      >
        <SessionList />
        <RecentActivity limit={100} />
      </div>
    </div>
  );
}
