import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useAppInfo } from '@blocklet/ui-react/lib/Dashboard';
import { Switch, usePaymentContext } from '@blocklet/payment-react';
import { Chip, Stack } from '@mui/material';
import React, { isValidElement, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import Tabs from '@arcblock/ux/lib/Tabs';
import Layout from '../../components/layout/admin';
import ProgressBar, { useTransitionContext } from '../../components/progress-bar';
import { useSessionContext } from '../../contexts/session';

const groups = {
  overview: React.lazy(() => import('./overview')),
  payments: React.lazy(() => import('./payments/index')),
  customers: React.lazy(() => import('./customers/index')),
  products: React.lazy(() => import('./products/index')),
  billing: React.lazy(() => import('./billing/index')),
  tax: React.lazy(() => import('./tax')),
  developers: React.lazy(() => import('./developers/index')),
  settings: React.lazy(() => import('./settings/index')),
};

// eslint-disable-next-line @typescript-eslint/no-shadow
const renderNav = (group: string, onChange: Function, groups: { label: string; value: string }[]) =>
  groups.map((x) => (
    <Chip
      key={x.value}
      variant={group === x.value ? 'filled' : 'outlined'}
      color={group === x.value ? 'primary' : 'default'}
      size="small"
      label={x.label}
      onClick={() => onChange(x.value)}
      sx={{
        mr: 2,
        fontSize: 14,
        fontWeight: 600,
        border: 'none',
        cursor: 'pointer',
        '&:hover': group === x.value ? {} : { backgroundColor: 'grey.100' },
      }}
    />
  ));

function Admin() {
  const navigate = useNavigate();
  const { t } = useLocaleContext();
  const { updateAppInfo } = useAppInfo();
  const settings = usePaymentContext();
  const { group = 'overview' } = useParams();
  const { isPending, startTransition } = useTransitionContext();

  const onLivemodeChange = (e: any) => {
    settings.setLivemode(!e.target.checked);
  };

  const onTabChange = (newTab: string) => {
    startTransition(() => {
      navigate(`/admin/${newTab}`);
    });
  };

  // @ts-ignore
  const TabComponent = groups[group] || groups.overview;

  const group1 = [
    { label: t('admin.overview'), value: 'overview' },
    { label: t('admin.payments'), value: 'payments' },
    { label: t('admin.customers'), value: 'customers' },
    { label: t('admin.products'), value: 'products' },
    { label: t('admin.tax'), value: 'tax' },
    { label: t('admin.billing'), value: 'billing' },
    { label: t('admin.settings'), value: 'settings' },
  ];

  const group2 = [{ label: t('admin.developers'), value: 'developers' }];

  useEffect(() => {
    updateAppInfo({
      description: t('admin.description'),
    });
  }, [t]);

  return (
    <>
      <ProgressBar pending={isPending} />
      <Stack
        direction="row"
        spacing={1}
        sx={{
          alignItems: 'center',
          justifyContent: 'end',
          flexWrap: 'wrap',
          mt: 1,
          pb: 2,
        }}>
        {/* <Box>{renderNav(group, onTabChange, group1)}</Box> */}
        {/* @ts-ignore */}
        <Tabs
          // @ts-ignore
          tabs={group1}
          // @ts-ignore
          current={group}
          // @ts-ignore
          onChange={onTabChange}
          scrollButtons="auto"
          variant="scrollable"
          sx={{
            flex: '1 0 auto',
            maxWidth: '100%',
            '.MuiTab-root': {
              marginBottom: '12px',
              fontWeight: '500',
              color: 'text.lighter',
              '&.Mui-selected': {
                color: 'primary.main',
              },
            },
            '.MuiTouchRipple-root': {
              display: 'none',
            },
          }}
        />
        <Stack
          direction="row"
          sx={{
            alignItems: 'center',
          }}>
          {renderNav(group, onTabChange, group2)}
          <label
            htmlFor="livemode-switch"
            style={{
              fontSize: 14,
              fontWeight: 600,
              cursor: 'pointer',
              color: settings.livemode ? 'text.primary' : 'warning.light',
            }}>
            {t('common.livemode')}
            <Switch
              id="livemode-switch"
              sx={{ ml: 1 }}
              variant="warning"
              checked={!settings.livemode}
              onChange={onLivemodeChange}
            />
          </label>
        </Stack>
      </Stack>
      <div className="page-content" key={settings.livemode ? 'live' : 'test'}>
        {isValidElement(TabComponent) ? TabComponent : <TabComponent />}
      </div>
    </>
  );
}

export default function WrappedAdmin() {
  const navigate = useNavigate();
  const { session } = useSessionContext();

  useEffect(() => {
    if (session.user && ['owner', 'admin'].includes(session.user.role) === false) {
      navigate('/customer');
    }
  }, [session.user]);

  return (
    <Layout>
      <Admin />
    </Layout>
  );
}
