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

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

const ProductCreate = React.lazy(() => import('./products/create'));
const ProductDetail = React.lazy(() => import('./products/detail'));
const PriceDetail = React.lazy(() => import('./prices/detail'));
const PaymentLinkCreate = React.lazy(() => import('./links/create'));
const PaymentLinkDetail = React.lazy(() => import('./links/detail'));
const PricingTableCreate = React.lazy(() => import('./pricing-tables/create'));
const PricingTableDetail = React.lazy(() => import('./pricing-tables/detail'));
const CouponDetail = React.lazy(() => import('./coupons/detail'));
const PromotionCodeDetail = React.lazy(() => import('./promotion-codes/detail'));
const VendorCreate = React.lazy(() => import('./vendors/create'));

const pages = {
  products: React.lazy(() => import('./products')),
  coupons: React.lazy(() => import('./coupons')),
  links: React.lazy(() => import('./links')),
  'pricing-tables': React.lazy(() => import('./pricing-tables')),
  passports: React.lazy(() => import('./passports')),
  vendors: React.lazy(() => import('./vendors')),
  'exchange-rate-providers': React.lazy(() => import('./exchange-rate-providers')),
};

export default function Products() {
  const navigate = useNavigate();
  const { t } = useLocaleContext();
  const { page = 'products', id, subpage } = useParams();
  const [createProduct, setCreateProduct] = useState(false);
  const [createCoupon, setCreateCoupon] = useState(false);
  const { startTransition } = useTransitionContext();
  const handleCreateProvider = () =>
    startTransition(() => navigate('/admin/products/exchange-rate-providers?create=1'));

  // Handle old-style routing where ID is passed as page parameter
  if (page.startsWith('prod_')) {
    return <ProductDetail id={page} />;
  }

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

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

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

  if (page === 'coupons' && subpage === 'promotion-codes' && id) {
    return <PromotionCodeDetail id={id} />;
  }

  if (page === 'coupons' && id && !subpage) {
    return <CouponDetail id={id} />;
  }

  if (page === 'promotion-codes' && id) {
    return <PromotionCodeDetail id={id} />;
  }

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

  if (page.startsWith('pv_')) {
    // 供应商详情页面暂时跳转到列表
    return <TabComponent />;
  }
  const tabs = [
    { label: t('admin.products'), value: 'products' },
    { label: t('admin.coupons'), value: 'coupons' },
    { label: t('admin.paymentLinks'), value: 'links' },
    { label: t('admin.pricingTables'), value: 'pricing-tables' },
    { label: t('admin.passports'), value: 'passports' },
    { label: t('admin.vendors'), value: 'vendors' },
    { label: t('admin.exchangeRateProvider.title'), value: 'exchange-rate-providers' },
  ];

  let extra = null;
  if (page === 'products') {
    extra = <ProductCreate open={createProduct} onClose={() => setCreateProduct(false)} />;
  } else if (page === 'links') {
    extra = <PaymentLinkCreate />;
  } else if (page === 'pricing-tables') {
    extra = <PricingTableCreate />;
  } else if (page === 'coupons') {
    extra = <CouponCreate open={createCoupon} onClose={() => setCreateCoupon(false)} />;
  } else if (page === 'vendors') {
    extra = <VendorCreate open={createProduct} onClose={() => setCreateProduct(false)} />;
  } else if (page === 'exchange-rate-providers') {
    extra = (
      <Button variant="contained" startIcon={<AddOutlined />} onClick={handleCreateProvider} size="small">
        {t('admin.exchangeRateProvider.create.primaryAction')}
      </Button>
    );
  }

  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={(newTab: string) => startTransition(() => navigate(`/admin/products/${newTab}`))}
          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>{extra}</Box>
      </Stack>
      {isValidElement(TabComponent) ? TabComponent : <TabComponent />}
    </>
  );
}
