import { Stack, Typography, TextField, Card } from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useState, useMemo } from 'react';

import type { TPaymentCurrency } from '@blocklet/payment-types';
import ProductCard from '../../payment/product-card';
import {
  formatPrice,
  formatNumber,
  formatDynamicPrice,
  formatUsdAmount,
  formatExchangeRate,
  formatToDatetime,
  formatCreditForCheckout,
} from '../../libs/util';
import QuoteDetailsPanel from '../quote-details-panel';
import type { SlippageConfigValue } from '../slippage-config';

interface ExchangeRateData {
  rate?: string;
  provider_name?: string;
  provider_id?: string;
  provider_display?: string; // Human-readable: "CoinGecko" or "CoinGecko (2 sources)"
  timestamp_ms?: number;
}

interface AutoTopupProductCardProps {
  product: any;
  price: any;
  currency: TPaymentCurrency;
  quantity: number;
  onQuantityChange: (quantity: number) => void;
  maxQuantity?: number;
  minQuantity?: number;
  creditCurrency: TPaymentCurrency;
  exchangeRate?: string | null;
  isDynamicPricing?: boolean;
  exchangeRateData?: ExchangeRateData | null;
  slippageConfig?: SlippageConfigValue | null;
  slippagePercent?: number;
  onSlippageChange?: (config: SlippageConfigValue) => void;
  disabled?: boolean;
}

export default function AutoTopupProductCard({
  product,
  price,
  currency,
  quantity,
  onQuantityChange,
  maxQuantity = 99,
  minQuantity = 1,
  creditCurrency,
  exchangeRate = null,
  isDynamicPricing = false,
  exchangeRateData = null,
  slippageConfig = null,
  slippagePercent = 0.5,
  onSlippageChange = undefined,
  disabled = false,
}: AutoTopupProductCardProps) {
  const { t, locale } = useLocaleContext();
  const [localQuantity, setLocalQuantity] = useState<number | undefined>(quantity);
  const localQuantityNum = Number(localQuantity) || 0;

  // Calculate payment amount for dynamic pricing
  const { paymentAmount, usdReferenceDisplay } = useMemo(() => {
    if (!isDynamicPricing || !exchangeRate || !price?.base_amount) {
      // Fixed pricing: use existing formatPrice
      return {
        paymentAmount: formatPrice(price, currency, product?.unit_label, localQuantity, true),
        usdReferenceDisplay: null,
      };
    }

    // Dynamic pricing: calculate token amount from base_amount / exchange_rate
    const baseAmount = Number(price.base_amount) * localQuantityNum;
    const rate = Number(exchangeRate);
    if (rate <= 0 || !Number.isFinite(baseAmount)) {
      return {
        paymentAmount: formatPrice(price, currency, product?.unit_label, localQuantity, true),
        usdReferenceDisplay: null,
      };
    }

    const tokenAmount = baseAmount / rate;
    const formattedToken = formatDynamicPrice(tokenAmount, true, 6);
    const formattedUsd = formatUsdAmount(baseAmount.toString(), locale);

    return {
      paymentAmount: `${formattedToken} ${currency.symbol}`,
      usdReferenceDisplay: formattedUsd ? `≈ $${formattedUsd}` : null,
    };
  }, [isDynamicPricing, exchangeRate, price, currency, product?.unit_label, localQuantity, localQuantityNum, locale]);

  const handleQuantityChange = (newQuantity: number) => {
    if (!newQuantity) {
      setLocalQuantity(undefined);
      return;
    }
    if (newQuantity >= minQuantity && newQuantity <= maxQuantity) {
      setLocalQuantity(newQuantity);
      onQuantityChange(newQuantity);
    }
  };

  const handleQuantityInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(event.target.value || '0', 10);
    if (!Number.isNaN(value)) {
      handleQuantityChange(value);
    }
  };

  const creditUnitAmount = Number(price.metadata?.credit_config?.credit_amount || 0);
  return (
    <Card variant="outlined" sx={{ p: 2 }}>
      <Stack
        direction="row"
        spacing={2}
        sx={{
          flexDirection: {
            xs: 'column',
            sm: 'row',
          },
          alignItems: {
            xs: 'flex-start',
            sm: 'center',
          },
          justifyContent: {
            xs: 'flex-start',
            sm: 'space-between',
          },
        }}>
        <Stack
          direction="row"
          spacing={2}
          sx={{
            alignItems: 'center',
            flex: 1,
          }}>
          <ProductCard
            name={product?.name || ''}
            description={t('payment.autoTopup.creditsIncluded', {
              num: formatCreditForCheckout(
                formatNumber(creditUnitAmount * localQuantityNum),
                creditCurrency?.symbol || '',
                locale
              ),
            })}
            logo={product?.images?.[0] as string}
            size={40}
          />
        </Stack>
        <Stack
          direction="row"
          spacing={1}
          sx={{
            alignItems: 'center',
            alignSelf: {
              xs: 'flex-end',
              sm: 'center',
            },
          }}>
          <Typography
            variant="body2"
            sx={{
              color: 'text.secondary',
              minWidth: 'fit-content',
            }}>
            {t('common.quantity')}:
          </Typography>
          <TextField
            size="small"
            value={localQuantity}
            onChange={handleQuantityInputChange}
            type="number"
            sx={{
              '& .MuiInputBase-root': {
                height: 32,
              },
            }}
            slotProps={{
              htmlInput: {
                min: 0,
                max: maxQuantity,
                style: { textAlign: 'center', padding: '4px 8px' },
              },
            }}
          />
        </Stack>
      </Stack>
      {/* 充值金额显示 */}
      <Stack
        direction="row"
        sx={{
          justifyContent: 'space-between',
          alignItems: 'flex-start',
          mt: 2,
          pt: 2,
          borderTop: '1px solid',
          borderColor: 'divider',
        }}>
        <Typography
          variant="body2"
          sx={{
            color: 'text.secondary',
          }}>
          {t('payment.autoTopup.rechargeAmount')}
        </Typography>
        <Stack sx={{ alignItems: 'flex-end' }}>
          <Typography
            variant="h6"
            sx={{
              fontWeight: 600,
              color: 'text.primary',
            }}>
            {paymentAmount}
          </Typography>
          {usdReferenceDisplay && (
            <Typography
              sx={{
                fontSize: '0.7875rem',
                color: 'text.lighter',
              }}>
              {usdReferenceDisplay}
            </Typography>
          )}
          {/* Dynamic Pricing - Exchange Rate Panel */}
          {isDynamicPricing && exchangeRateData?.rate && (
            <QuoteDetailsPanel
              rateLine={t('payment.checkout.quote.rateLine', {
                symbol: currency.symbol,
                rate: `$${formatExchangeRate(exchangeRateData.rate) || exchangeRateData.rate}`,
              })}
              rows={[
                {
                  label: t('payment.checkout.quote.detailProvider'),
                  value: exchangeRateData?.provider_display || exchangeRateData?.provider_name || '—',
                },
                {
                  label: t('payment.checkout.quote.detailUpdatedAt'),
                  value: exchangeRateData?.timestamp_ms ? formatToDatetime(exchangeRateData.timestamp_ms, locale) : '—',
                },
                {
                  label: t('payment.checkout.quote.detailSlippage'),
                  value:
                    slippageConfig?.mode === 'rate' && slippageConfig.min_acceptable_rate
                      ? `$${formatExchangeRate(slippageConfig.min_acceptable_rate) || slippageConfig.min_acceptable_rate}`
                      : `${slippageConfig?.percent ?? slippagePercent}%`,
                  isSlippage: true,
                },
              ]}
              isSubscription
              slippageValue={slippageConfig?.percent ?? slippagePercent}
              slippageConfig={slippageConfig || undefined}
              onSlippageChange={onSlippageChange}
              exchangeRate={exchangeRateData?.rate}
              baseCurrency="USD"
              disabled={disabled}
            />
          )}
        </Stack>
      </Stack>
    </Card>
  );
}
