import * as React from "react";
import {
  Box,
  Container,
  CircularProgress,
  Alert
} from "@mui/material";

import DashboardComponent from "./components/Dashboard";
import { configuration } from "./dashboard-config";
import { useDashboardData } from "./features/dashboard";

export default function Dashboard() {
  const [mode, setMode] = React.useState<"expense" | "income">("expense");
  const { data, latest, isLoading, error } = useDashboardData(mode);

  if (isLoading) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Container sx={{ mt: 4 }}>
        <Alert severity="error">{String(error)}</Alert>
      </Container>
    );
  }

  if (!data) {
    return null;
  }

  return (
    <DashboardComponent
      config={configuration}
      data={data}
      latest={latest}
      onModeChange={(newMode) => setMode(newMode)}
    />
  );
}
