/* eslint-disable react-hooks/exhaustive-deps */
import { PaymentProvider } from '@blocklet/payment-react';
import Dashboard from '@blocklet/ui-react/lib/Dashboard';
import { styled } from '@mui/system';
import { useEffect } from 'react';

import { Box, CircularProgress } from '@mui/material';
import { useSessionContext } from '../../contexts/session';

function LayoutLoading() {
  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <CircularProgress />
    </Box>
  );
}

// window.blocklet is bootstrapped synchronously in public/index.html (CF) but
// the full payload is overlaid from /__blocklet__.js. Don't render children
// (which may fire API requests on mount) until the critical fields are in
// place — otherwise requests go out against a half-initialized config and
// can cascade into auth failures / unintended redirects.
function isBlockletReady() {
  const b = (window as any).blocklet;
  return !!(b && b.appPid && b.prefix);
}

const Root = styled(Dashboard)<{ padding: string }>`
  width: 100%;
  background-color: ${({ theme }) => theme.palette.background.default};

  > .dashboard-body > .dashboard-main {
    > .dashboard-content {
      padding: ${(props) => props.padding || '0 24px'};
      .MuiTab-root {
        padding: 0;
        margin-right: 24px;
        min-height: 32px;
        min-width: auto;
        font-size: 0.875rem;
      }
      .page-content .MuiTab-root {
        font-size: 0.875rem;
        &.Mui-selected {
          font-size: 1.125rem;
        }
      }

      .MuiTabs-root {
        min-height: 32px;
        margin-bottom: 8px;
      }

      .page-content {
        margin-top: 2px;
      }

      .MuiToggleButton-root {
        padding: 4px 16px;
      }
    }

    > .dashboard-footer {
      margin-top: 0;
      padding: 8px 0;

      .logo-container {
        svg {
          height: 100%;
        }
      }
    }
  }
  @media (max-width: ${({ theme }) => theme.breakpoints.values.md}px) {
    > .dashboard-body > .dashboard-main > .dashboard-content {
      padding: ${(props) => props.padding || '0 16px'};
    }
  }
`;

export default function Layout(props: any) {
  const { session, connectApi, events } = useSessionContext();

  useEffect(() => {
    events.once('logout', () => {
      window.location.href = window?.blocklet?.prefix || '/';
    });
  }, []);

  useEffect(() => {
    if (session.initialized && !session.user) {
      // @ts-ignore
      session.login(() => {}, { openMode: 'redirect', redirect: window.location.href });
    }
  }, [session.initialized]);

  // Show a loading state — not a "Redirecting..." text and not a blank page —
  // while either window.blocklet or the session is still resolving. Admin
  // pages fire authenticated API requests on mount, so children must not
  // render until both are fully in place.
  if (!isBlockletReady() || !session.initialized) {
    return <LayoutLoading />;
  }

  if (session.user) {
    return (
      <PaymentProvider session={session} connect={connectApi}>
        <Root {...props} footerProps={{ className: 'dashboard-footer' }} />
      </PaymentProvider>
    );
  }

  // Session initialized but not logged in: the effect above triggers a
  // redirect-based login. Keep showing the loading state (instead of a
  // "Redirecting..." text) so the user isn't confused when the actual
  // navigation hasn't happened yet.
  return <LayoutLoading />;
}
