import Tabs from '@arcblock/ux/lib/Tabs';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Box, Stack } from '@mui/material';
import React, { isValidElement } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

import { useTransitionContext } from '../../../components/progress-bar';
import TaxRateCreate from './create';

const TaxRatesList = React.lazy(() => import('./list'));
const TaxRateDetail = React.lazy(() => import('./detail'));

const pages = {
  rates: TaxRatesList,
};

export default function TaxIndex() {
  const navigate = useNavigate();
  const { t } = useLocaleContext();
  const { page = 'rates' } = useParams();
  const { startTransition } = useTransitionContext();

  if (page.startsWith('txr_')) {
    return <TaxRateDetail id={page} />;
  }

  // @ts-ignore
  const TabComponent = pages[page] || pages.rates;

  const tabs = [{ label: t('admin.taxRates'), value: 'rates' }];

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

  return (
    <>
      <Stack
        direction="row"
        spacing={1}
        sx={{
          alignItems: 'flex-start',
          justifyContent: 'end',
          flexWrap: 'wrap',
        }}>
        {/* @ts-ignore */}
        <Tabs
          // @ts-ignore
          tabs={tabs}
          // @ts-ignore
          current={page}
          // @ts-ignore
          onChange={onTabChange}
          scrollButtons="auto"
          variant="scrollable"
          sx={{
            flex: '1 0 auto',
            maxWidth: '100%',
            '.MuiTab-root': {
              color: 'text.lighter',
            },
            '.MuiTabs-indicator': {
              display: 'none',
            },
            '.Mui-selected': {
              fontSize: 24,
              color: 'text.primary',
            },
            '.MuiTabs-hideScrollbar': {
              border: 'none !important',
            },
            '.MuiTouchRipple-root': {
              display: 'none',
            },
          }}
        />
        <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
          <TaxRateCreate />
        </Box>
      </Stack>
      {isValidElement(TabComponent) ? TabComponent : <TabComponent />}
    </>
  );
}
