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

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

const PaymentIntentDetail = React.lazy(() => import('./intents/detail'));
const RefundDetail = React.lazy(() => import('./refunds/detail'));
const PayoutDetail = React.lazy(() => import('./payouts/detail'));

const pages = {
  intents: React.lazy(() => import('./intents')),
  refunds: React.lazy(() => import('./refunds')),
  payouts: React.lazy(() => import('./payouts')),
};

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

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

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

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

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

  // @ts-ignore
  const TabComponent = pages[page] || pages.intents;
  const tabs = [
    { label: t('admin.paymentIntent.list'), value: 'intents' },
    { label: t('admin.refunds'), value: 'refunds' },
    { label: t('admin.payouts'), value: 'payouts' },
  ];

  return (
    <div>
      {/* @ts-ignore */}
      <Tabs
        // @ts-ignore
        tabs={tabs}
        // @ts-ignore
        current={page}
        // @ts-ignore
        onChange={onTabChange}
        scrollButtons="auto"
        variant="scrollable"
        sx={{
          '.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',
          },
        }}
      />
      {isValidElement(TabComponent) ? TabComponent : <TabComponent />}
    </div>
  );
}
