import * as React from 'react';
import CssBaseline from '@mui/material/CssBaseline';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import AppTheme from '../shared-theme/AppTheme';
import MainContent from './components/MainContent';
import Article from './components/Article';
import Latest from './components/Latest';
import Footer from './components/Footer';
import Login from './components/Login';
import Register from './components/Register';
import Profile from './components/Profile';
import { useArticles } from './providers/Article';
import { useAuth } from './providers/Author';

type View = 'home' | 'login' | 'register' | 'article' | 'profile';

export default function Blog(props: { disableCustomTheme?: boolean }) {
  const { articles, loading, error } = useArticles();
  const { currentUser } = useAuth();

  const [selectedArticle, setSelectedArticle] = React.useState<number | null>(null);
  const [showLogin, setShowLogin] = React.useState(false);
  const [showRegister, setShowRegister] = React.useState(false);
  const [showProfile, setShowProfile] = React.useState(false);

  const handleSelectArticle = (index: number) => {
    setSelectedArticle(index);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleBack = () => setSelectedArticle(null);

  const handleShowLogin = () => {
    setShowLogin(true);
    setShowRegister(false);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  const handleShowRegister = () => {
    setShowRegister(true);
    setShowLogin(false);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  const handleHideAuth = () => {
    setShowLogin(false);
    setShowRegister(false);
  };
  const handleShowProfile = () => {
    setShowProfile(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  const handleHideProfile = () => {
    setShowProfile(false);
  };

  // derive a single source of truth for view
  const view: View = React.useMemo(() => {
    if (selectedArticle !== null) return 'article';
    if (showRegister) return 'register';
    if (showLogin) return 'login';
    if (showProfile) return 'profile';
    return 'home';
  }, [selectedArticle, showLogin, showRegister, showProfile]);

  // render function keeps JSX tidy
  const renderView = () => {
    switch (view) {
      case 'register':
        return <Register onBack={handleHideAuth} />;
      case 'login':
        return (
          <Login
            onBack={handleHideAuth}
            onRegister={() => {
              handleShowRegister();
            }}
          />
        );
      case 'profile':
        return (
          <Profile
            onBack={handleHideProfile}
          />
        );
      case 'article':
        if (selectedArticle == null || !articles[selectedArticle]) return null;
        return <Article article={articles[selectedArticle]} onBack={handleBack} />;
      case 'home':
      default:
        return (
          <>
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 2, gap: 1 }}>
              {!currentUser ? (
                <>
                  <Button
                    variant="outlined"
                    color="primary"
                    onClick={handleShowLogin}
                  >
                    Login
                  </Button>
                </>
              ) : (
                <>
                  <Button
                    variant="outlined"
                    color="primary"
                    onClick={() => setShowProfile(true)}
                  >
                    {currentUser.username}
                  </Button>
                </>
              )}
            </Box>

            <MainContent articles={articles} onSelectArticle={handleSelectArticle} />
            <Latest
              articles={articles}
              onSelectArticle={handleSelectArticle}
              onLoadMore={async () => {}}
            />
          </>
        );
    }
  };

  if (loading) {
    return (
      <AppTheme {...props}>
        <CssBaseline enableColorScheme />
        <Container
          maxWidth="lg"
          component="main"
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}
        >
          Loading articles...
        </Container>
      </AppTheme>
    );
  }

  if (error) {
    return (
      <AppTheme {...props}>
        <CssBaseline enableColorScheme />
        <Container
          maxWidth="lg"
          component="main"
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}
        >
          Failed to load articles: {error}
        </Container>
      </AppTheme>
    );
  }

  return (
    <AppTheme {...props}>
      <CssBaseline enableColorScheme />

      <Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
        <Container
          maxWidth="lg"
          component="main"
          sx={{
            flex: '1 0 auto',
            display: 'flex',
            flexDirection: 'column',
            my: 4,
            gap: 4,
            pb: view === 'home' ? 24 : 0,
          }}
        >
          {renderView()}
        </Container>

        {view === 'home' && (
          <Box
            component="footer"
            sx={{
              position: 'fixed',
              bottom: 0,
              left: 0,
              right: 0,
              zIndex: 1000,
              bgcolor: 'background.paper',
              boxShadow: '0 -2px 10px rgba(0,0,0,0.08)',
            }}
          >
            <Footer />
          </Box>
        )}
      </Box>
    </AppTheme>
  );
}
