import { useEffect, useState } from 'react';
import { UserLayout } from './user/UserLayout';
import { UserListPage } from './user/UserListPage';
import {AdminLayout} from "./admin/layout/AdminLayout.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' ? (
        <AdminLayout children={undefined}>
        </AdminLayout>
      ) : (
        <UserLayout>
          <UserListPage />
        </UserLayout>
      )}
    </>
  );
}
