import { useEffect, useState } from 'react';
import {Navigate, Route, Routes} from 'react-router-dom';
import { UserLayout } from './user/UserLayout';
import { UserListPage } from './user/UserListPage';
import {AdminRoute} from "./admin/route/AdminRoute.tsx";
import {ToastContainer} from "react-toastify";
import {UserContentPreviewPage} from "./user/UserContentPreviewPage.tsx";

type Skin = 'admin' | 'user';

function getInitialSkin(): Skin {
  const params = new URLSearchParams(window.location.search);
  return params.get('skin') === 'user' ? 'user' : 'admin';
}

function switchSkin(nextSkin: Skin) {
  const url = new URL(window.location.href);
  url.searchParams.set('skin', nextSkin);
  window.location.href = url.toString();
}

export default function App() {
  const [skin] = useState<Skin>(getInitialSkin);
  const [styleReady, setStyleReady] = useState(false);

  useEffect(() => {
    let mounted = true;

    document.body.dataset.skin = skin;

    const loadStyles = skin === 'admin' ? import('./admin') : import('./user');
    loadStyles.finally(() => {
      if (mounted) {
        setStyleReady(true);
      }
    });

    return () => {
      mounted = false;
    };
  }, [skin]);

  if (!styleReady) {
    return <div style={{ padding: 24 }}>Loading publishing styles...</div>;
  }

  return (
    <>
      <div className="skin_switcher">
        <button type="button" className={skin === 'admin' ? 'active' : ''} onClick={() => switchSkin('admin')}>
          Admin layout
        </button>
        <button type="button" className={skin === 'user' ? 'active' : ''} onClick={() => switchSkin('user')}>
          User layout
        </button>
      </div>

      {skin === 'admin' ? (
        <AdminRoute />
      ) : (
        <Routes>
          <Route
            path="/preview/content"
            element={(
              <UserLayout title="콘텐츠 미리보기">
                <UserContentPreviewPage />
              </UserLayout>
            )}
          />
          <Route
            path="/"
            element={(
              <UserLayout>
                <UserListPage />
              </UserLayout>
            )}
          />
          <Route path="*" element={<Navigate to="/?skin=user" replace />} />
        </Routes>
      )}
      <ToastContainer position="bottom-right" autoClose={3000} />
    </>
  );
}
