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

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

const EventDetail = React.lazy(() => import('./events/detail'));
const WebhookDetail = React.lazy(() => import('./webhooks/detail'));

const pages = {
  webhooks: React.lazy(() => import('./webhooks')),
  events: React.lazy(() => import('./events')),
};

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

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

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

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

  // @ts-ignore
  const TabComponent = pages[page] || pages.webhooks;
  const tabs = [
    { label: t('admin.webhooks'), value: 'webhooks' },
    { label: t('admin.events.title'), value: 'events' },
  ];

  return (
    <div>
      <Typography variant="h5" sx={{ mb: 1 }}>
        {t('admin.developers')}
      </Typography>
      {/* @ts-ignore */}
      <Tabs
        // @ts-ignore
        tabs={tabs}
        // @ts-ignore
        current={page}
        // @ts-ignore
        onChange={onTabChange}
        scrollButtons="auto"
      />
      {isValidElement(TabComponent) ? TabComponent : <TabComponent />}
    </div>
  );
}
