import { useEffect, useState } from 'react';
import AuthGate from './components/AuthGate';
import EditorShell from './components/EditorShell';
import PostsList from './components/PostsList';
import Settings from './components/Settings';
import AdminTopBar from './components/layout/AdminTopBar';
import { Box } from '@mui/material';
import './App.css';

function App() {
  const [authenticated, setAuthenticated] = useState(false);
  const [selectedPostId, setSelectedPostId] = useState<string | null>(null);
  const [showSettings, setShowSettings] = useState(false);

  useEffect(() => {
    const flag = localStorage.getItem('voxblog_authed');
    setAuthenticated(flag === '1');
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('voxblog_authed');
    localStorage.removeItem('voxblog_post_id');
    localStorage.removeItem('voxblog_draft_id');
    setAuthenticated(false);
    setSelectedPostId(null);
  };

  const createNewPost = async () => {
    try {
      const res = await fetch('/api/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'Untitled', contentHtml: '<p></p>', status: 'editing' }),
      });
      const data = await res.json();
      if (res.ok && data.id) {
        setSelectedPostId(data.id);
        localStorage.setItem('voxblog_post_id', data.id);
      } else {
        alert('Failed to create post');
      }
    } catch (e: any) {
      alert('Failed to create post: ' + (e?.message || 'unknown error'));
    }
  };

  return (
    <>
      {authenticated ? (
        <Box sx={{ display: 'grid', gridTemplateRows: 'auto 1fr', minHeight: '100dvh', width: '100%' }}>
          <AdminTopBar
            userName={undefined}
            onGoPosts={() => {
              setSelectedPostId(null);
              setShowSettings(false);
            }}
            onSettings={() => {
              setSelectedPostId(null);
              setShowSettings(true);
            }}
            onLogout={handleLogout}
          />
          <Box sx={{ minHeight: 0, overflow: 'hidden', width: '100%' }}>
            {showSettings ? (
              <Settings onBack={() => setShowSettings(false)} />
            ) : selectedPostId ? (
              <EditorShell
                onLogout={handleLogout}
                initialPostId={selectedPostId}
                onBack={() => setSelectedPostId(null)}
              />
            ) : (
              <PostsList
                onSelect={(id) => {
                  setSelectedPostId(id);
                  localStorage.setItem('voxblog_post_id', id);
                }}
                onNew={createNewPost}
              />
            )}
          </Box>
        </Box>
      ) : (
        <AuthGate onAuth={() => {
          localStorage.setItem('voxblog_authed', '1');
          setAuthenticated(true);
        }} />
      )}
    </>
  );
}

export default App;
