import React from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import { Box, CircularProgress } from "@mui/material";
import { useAppContext } from "../context/AppContext";
import { Layout } from "./Layout";
import { ResourceList } from "./ResourceList";
import { ResourceForm } from "./ResourceForm";
import { ResourceDetail } from "./ResourceDetail";
import { ValidationAlert } from "./ValidationAlert";

interface AdminProps {
  basePath: string;
}

export function Admin({ basePath }: AdminProps) {
  const { resources, loading, errors, warnings } = useAppContext();

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

  if (errors.length > 0) {
    return <ValidationAlert errors={errors} warnings={warnings} />;
  }

  if (resources.length === 0) {
    return (
      <Box sx={{ p: 4, textAlign: "center" }}>
        No resources found in the OpenAPI spec with x-resource defined.
      </Box>
    );
  }

  return (
    <>
      {warnings.length > 0 && <ValidationAlert errors={[]} warnings={warnings} />}
      <Layout resources={resources} basePath={basePath}>
        <Routes>
          <Route index element={<Navigate to={`${basePath}/${resources[0].name}`} replace />} />
          {resources.map((r) => (
            <React.Fragment key={r.name}>
              <Route path={r.name} element={<ResourceList resource={r} basePath={basePath} />} />
              {!r.streaming && (
                <>
                  <Route path={`${r.name}/new`} element={<ResourceForm resource={r} basePath={basePath} mode="create" />} />
                  <Route path={`${r.name}/:id`} element={<ResourceDetail resource={r} basePath={basePath} />} />
                  <Route path={`${r.name}/:id/edit`} element={<ResourceForm resource={r} basePath={basePath} mode="edit" />} />
                </>
              )}
            </React.Fragment>
          ))}
        </Routes>
      </Layout>
    </>
  );
}
