import * as React from "react";
import { useAuth, AuthPage } from "../react-auth";
import { UploadProvider } from "./providers/UploadProvider";
import AdminLayout from "./components/AdminLayout";
import ResourceView from "./components/ResourceView";
import { getAppConfig } from "./config";
import { initializeApiClients } from "./api/client";
import { AppConfig } from "./types/config";
import { FieldComponents } from "./types/overrides";
import { Box, Typography, Paper, CircularProgress } from "@mui/material";
import {
  Routes,
  Route,
  useNavigate,
  useParams,
} from "react-router-dom";

import { ConfigContext } from "./providers/ConfigContext";
import ProfileView from "./components/ProfileView";

function DefaultDashboard({ basePath }: { basePath: string }) {
  const config = React.useContext(ConfigContext);
  const navigate = useNavigate();

  const resources = config?.resources || [];
  const visibleResources = resources.filter((res) => !res.hidden);

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Welcome to the Admin Panel
      </Typography>
      <Typography variant="body1" sx={{ color: 'text.secondary' }}>
        Select a resource from the sidebar to manage data.
      </Typography>
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
          gap: 3,
          mt: 4,
        }}
      >
        {visibleResources.map((res) => (
          <Paper
            key={res.name}
            sx={{
                p: 3,
                textAlign: "center",
                cursor: 'pointer',
                transition: 'transform 0.2s',
                '&:hover': { transform: 'translateY(-4px)', boxShadow: 4 }
            }}
            onClick={() => navigate(`/admin/${res.name}`)}
          >
            <Typography variant="h6" color="primary">{res.pluralLabel}</Typography>
            <Typography variant="body2" color="text.secondary">Manage {res.pluralLabel.toLowerCase()}</Typography>
          </Paper>
        ))}
      </Box>
    </Box>
  );
}

interface AdminAppProps {
  basePath: string;
  fieldComponents: FieldComponents;
  Dashboard?: React.ComponentType<{ basePath: string }>;
  Layout?: React.ComponentType<AdminLayoutProps>;
  LoginPage?: React.ComponentType<any>;
}

function AdminApp({ basePath, fieldComponents, Dashboard = DefaultDashboard, Layout = AdminLayout, LoginPage = AuthPage }: AdminAppProps) {
  const { currentUser, login, logout, loading, error } = useAuth();
  const config = React.useContext(ConfigContext);
  const navigate = useNavigate();

  const resources = config?.resources || [];
  const visibleResources = resources.filter((res) => !res.hidden);

  if (!currentUser) {
    return (
      <LoginPage
        mode="login"
        login={login}
        register={async () => {}}
        loading={loading}
        error={error}
        onSwitchMode={() => {}}
        onBack={() => {}}
        currentUser={null}
      />
    );
  }

  return (
    <Layout
      username={currentUser.username}
      onLogout={logout}
      onSelectResource={(name) => navigate(`/admin/${name}`)}
      resources={visibleResources}
    >
      <Routes>
        <Route path="/" element={<Dashboard basePath={basePath} />} />
        <Route path="/profile" element={<ProfileView />} />
        <Route path="/:resourceName" element={<ResourceRouteWrapper fieldComponents={fieldComponents} />} />
        <Route path="/:resourceName/:id" element={<ResourceRouteWrapper fieldComponents={fieldComponents} />} />
        <Route path="/:resourceName/create" element={<ResourceRouteWrapper fieldComponents={fieldComponents} />} />
        <Route path="/:resourceName/edit/:id" element={<ResourceRouteWrapper fieldComponents={fieldComponents} />} />
      </Routes>
    </Layout>
  );
}

function ResourceRouteWrapper({ fieldComponents }: { fieldComponents: FieldComponents }) {
  const { resourceName } = useParams();
  const config = React.useContext(ConfigContext);
  const selectedResource = config?.resources.find((r) => r.name === resourceName);

  if (!selectedResource) return <Typography>Resource not found</Typography>;

  return <ResourceView config={selectedResource} fieldComponents={fieldComponents} />;
}

interface AdminLayoutProps {
  children: React.ReactNode;
  onSelectResource: (resourceName: string | null) => void;
  onLogout: () => void;
  username?: string;
  resources: import("./types/config").ResourceConfig[];
}

interface AdminProps {
  basePath?: string;
  resourceOverrides?: Record<string, any>;
  profileConfig?: any;
  fieldComponents: FieldComponents;
  Dashboard?: React.ComponentType<{ basePath: string }>;
  Layout?: React.ComponentType<AdminLayoutProps>;
  LoginPage?: React.ComponentType<any>;
}

export default function Admin({ basePath = "/admin", resourceOverrides = {}, profileConfig = {}, fieldComponents, Dashboard, Layout, LoginPage }: AdminProps) {
  const existingConfig = React.useContext(ConfigContext);
  const [config, setConfig] = React.useState<AppConfig | null>(existingConfig);

  React.useEffect(() => {
    if (!existingConfig) {
      getAppConfig(resourceOverrides, profileConfig).then((cfg) => {
        initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
        setConfig(cfg);
      });
    }
  }, [resourceOverrides, profileConfig, existingConfig]);

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

  const content = (
    <UploadProvider>
      <AdminApp basePath={basePath} fieldComponents={fieldComponents} Dashboard={Dashboard} Layout={Layout} LoginPage={LoginPage} />
    </UploadProvider>
  );

  if (existingConfig) {
    return content;
  }

  return (
    <ConfigContext.Provider value={config}>
      {content}
    </ConfigContext.Provider>
  );
}
