import { Navigate, useNavigate, useParams } from 'react-router-dom'
import { useMe } from '@features/auth'
import { ROUTES } from '@shared/config/routes'
import { usePortfolio, useCreateWallet, CHAINS, type Chain } from '@features/wallet'
import { BalanceCard } from '@widgets/balance-card'
import { TokenTable, AllTokenTable } from '@widgets/token-table'
import { WalletHeader } from '@widgets/wallet-header'
import { WalletChainTabs } from '@widgets/wallet-chain-tabs'
import { Button, Spinner } from '@shared/ui'
import styles from './WalletPage.module.css'

export function WalletPage() {
  const { data, isLoading, isError } = useMe()
  const { error: portfolioError, isLoading: isPortfolioLoading } = usePortfolio()
  const { mutate: createWallet, isPending } = useCreateWallet()
  const navigate = useNavigate()
  const { chain: chainParam } = useParams<{ chain?: string }>()

  const noWallet = (portfolioError as { error?: string } | null)?.error?.includes('No wallets')

  if (isError) return <div className={styles.error}>Произошла ошибка. Попробуйте обновить страницу.</div>
  if (data && !data.kyc_verified) return <Navigate to={ROUTES.KYC} replace />

  const upper = chainParam?.toUpperCase() as Chain | undefined
  const chain: Chain | undefined = upper && CHAINS.includes(upper) ? upper : undefined

  return (
    <div className={styles.page}>
      <WalletHeader />
      <main className={styles.main}>
        <div className={styles.glow} />
        {isLoading || isPortfolioLoading ? (
          <Spinner fullscreen label="Загрузка" />
        ) : noWallet ? (
          <div className={styles.noWallet}>
            <p>У вас пока нет кошелька. Создайте его, чтобы начать.</p>
            <Button
              variant="outline"
              onClick={() => createWallet(undefined, { onSuccess: () => navigate(ROUTES.SEED_PHRASE) })}
              disabled={isPending}
            >
              {isPending ? 'Создание...' : 'Создать кошелёк'}
            </Button>
          </div>
        ) : (
          <>
            <BalanceCard />
            <WalletChainTabs />
            {chain ? <TokenTable chain={chain} /> : <AllTokenTable />}
          </>
        )}
      </main>
    </div>
  )
}
