import { useEffect, useState } from 'react';
import LogoMark from './LogoMark';
import TrackerScreen from './TrackerScreen';
import { getSession, logout, type SessionUser } from './api';

interface Props {
  /** API base — the remote server, or the on-device server in local mode. */
  baseUrl: string;
  /** Session is invalid — bounce back to the login screen. */
  onUnauthenticated: () => void;
  /** Signed out — return to first-run/login. */
  onSignOut: () => void;
}

type Tab = 'tracker' | 'calendar' | 'insights' | 'account';

const TABS: { id: Tab; label: string; icon: React.ReactNode }[] = [
  {
    id: 'tracker',
    label: 'Tracker',
    icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12h4l3 8 4-16 3 8h4" /></svg>,
  },
  {
    id: 'calendar',
    label: 'Calendar',
    icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="17" rx="2" /><path d="M3 9h18M8 2v4M16 2v4" /></svg>,
  },
  {
    id: 'insights',
    label: 'Insights',
    icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18" /><path d="M7 15l4-5 3 3 4-6" /></svg>,
  },
  {
    id: 'account',
    label: 'Account',
    icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></svg>,
  },
];

function Placeholder({ title, note }: { title: string; note: string }) {
  return (
    <div className="placeholder">
      <h2>{title}</h2>
      <p>{note}</p>
    </div>
  );
}

export default function MainApp({ baseUrl, onUnauthenticated, onSignOut }: Props) {
  const [tab, setTab] = useState<Tab>('tracker');
  const [user, setUser] = useState<SessionUser | null>(null);
  const [signingOut, setSigningOut] = useState(false);

  useEffect(() => {
    getSession(baseUrl).then(res => {
      if (res.status === 401) { onUnauthenticated(); return; }
      const u = res.data?.user ?? (res.data as SessionUser | undefined);
      if (u?.username) setUser(u);
    });
  }, [baseUrl, onUnauthenticated]);

  async function handleSignOut() {
    setSigningOut(true);
    await logout(baseUrl);
    onSignOut();
  }

  const initial = (user?.username || '?').charAt(0).toUpperCase();

  return (
    <div className="app">
      <header className="app-topbar">
        <LogoMark size={30} />
        <span className="app-topbar__word">Bill <b>Tracker</b></span>
        <span className="app-topbar__spacer" />
        <button className="avatar" onClick={() => setTab('account')} aria-label="Account">{initial}</button>
      </header>

      <main className="app-main" key={tab}>
        {tab === 'tracker' && <TrackerScreen baseUrl={baseUrl} onUnauthenticated={onUnauthenticated} />}
        {tab === 'calendar' && <Placeholder title="Calendar" note="A month-at-a-glance view of when bills are due is coming here next." />}
        {tab === 'insights' && <Placeholder title="Insights" note="Spending trends and this-vs-last-month comparisons are coming here next." />}
        {tab === 'account' && (
          <div className="app-state">
            <div className="avatar" style={{ width: 56, height: 56, fontSize: '1.5rem' }}>{initial}</div>
            <h2>{user?.username ?? 'Signed in'}</h2>
            <p>{user?.role === 'admin' ? 'Administrator' : 'Signed in to this device'}</p>
            <button className="btn-secondary" style={{ maxWidth: 220 }} onClick={handleSignOut} disabled={signingOut}>
              {signingOut ? 'Signing out…' : 'Sign out'}
            </button>
          </div>
        )}
      </main>

      <nav className="tabbar">
        {TABS.map(t => (
          <button
            key={t.id}
            className={'tab' + (tab === t.id ? ' is-active' : '')}
            onClick={() => setTab(t.id)}
            aria-current={tab === t.id ? 'page' : undefined}
          >
            {t.icon}
            <span>{t.label}</span>
          </button>
        ))}
      </nav>
    </div>
  );
}
