import { Skeleton } from '@mui/material'
import { useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { useChain } from '../../hooks/useChain.js'
import { useToken } from '../../hooks/useToken.js'
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js'
import { useChainOrderStore } from '../../stores/chains/ChainOrderStore.js'
import type { ChainOrderState } from '../../stores/chains/types.js'
import type { FormTypeProps } from '../../stores/form/types.js'
import { FormKeyHelper } from '../../stores/form/types.js'
import { useFieldValues } from '../../stores/form/useFieldValues.js'
import type { DisabledUIConfig } from '../../types/widget.js'
import { navigationRoutes } from '../../utils/navigationRoutes.js'
import { AvatarBadgedDefault, AvatarBadgedSkeleton } from '../Avatar/Avatar.js'
import { TokenAvatar } from '../Avatar/TokenAvatar.js'
import { CardTitle } from '../Card/CardTitle.js'
import {
  CardContent,
  SelectTokenCard,
  SelectTokenCardHeader,
} from './SelectTokenButton.style.js'

export const SelectTokenButton: React.FC<
  FormTypeProps & {
    hiddenReverse?: boolean
  }
> = ({ formType, hiddenReverse }) => {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const { disabledUI, mode } = useWidgetConfig()
  const tokenKey = FormKeyHelper.getTokenKey(formType)
  const [chainId, tokenAddress] = useFieldValues(
    FormKeyHelper.getChainKey(formType),
    tokenKey
  )
  const { chain, isLoading: isChainLoading } = useChain(chainId)
  const { token, isLoading: isTokenLoading } = useToken(chainId, tokenAddress)

  const isAllNetworks = useChainOrderStore(
    (state: ChainOrderState) => state[`${formType}IsAllNetworks`]
  )

  const handleClick = () => {
    navigate({
      to:
        formType === 'from'
          ? navigationRoutes.fromToken
          : mode === 'refuel'
            ? navigationRoutes.toTokenNative
            : navigationRoutes.toToken,
    })
  }

  const isSelected = !!(chain && token)
  const onClick = !disabledUI?.[tokenKey as keyof DisabledUIConfig]
    ? handleClick
    : undefined
  const defaultPlaceholder = `${t('main.select')}...`
  const cardTitle: string =
    formType === 'from' && mode === 'custom'
      ? t('header.payWith')
      : t(`main.${formType}`)
  return (
    <SelectTokenCard component="button" onClick={onClick}>
      <CardContent formType={formType} mask={!hiddenReverse}>
        <CardTitle>{cardTitle}</CardTitle>
        {chainId && tokenAddress && (isChainLoading || isTokenLoading) ? (
          <SelectTokenCardHeader
            avatar={<AvatarBadgedSkeleton />}
            title={<Skeleton variant="text" width={64} height={24} />}
            subheader={<Skeleton variant="text" width={72} height={16} />}
          />
        ) : (
          <SelectTokenCardHeader
            avatar={
              isSelected ? (
                <TokenAvatar token={token} chain={chain} />
              ) : (
                <AvatarBadgedDefault
                  chain={isAllNetworks ? undefined : chain}
                />
              )
            }
            title={isSelected ? token.symbol : defaultPlaceholder}
            slotProps={{
              title: {
                title: isSelected ? token.symbol : defaultPlaceholder,
              },
              subheader: {
                title: isSelected ? chain.name : undefined,
              },
            }}
            subheader={isSelected ? chain.name : null}
            selected={isSelected}
          />
        )}
      </CardContent>
    </SelectTokenCard>
  )
}
