/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  findCurrency,
  formatAmountPrecisionLimit,
  usePaymentContext,
  api,
  FormLabel,
  isCreditMetered,
  formatPrice,
  Collapse,
  formatNumber,
} from '@blocklet/payment-react';
import type {
  InferFormType,
  PriceRecurring,
  TMeter,
  TMeterExpanded,
  TPaymentCurrency,
  TPaymentMethodExpanded,
  TPrice,
  TPriceExpanded,
} from '@blocklet/payment-types';
import { DeleteOutlineOutlined } from '@mui/icons-material';
import {
  Alert,
  Box,
  Button,
  Checkbox,
  Collapse as MuiCollapse,
  FormControlLabel,
  IconButton,
  InputAdornment,
  MenuItem,
  Select,
  Stack,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
  Typography,
  Autocomplete,
  Divider,
} from '@mui/material';

import { styled } from '@mui/system';
import { Controller, useFieldArray, useFormContext, useWatch } from 'react-hook-form';
import type { LiteralUnion } from 'type-fest';
import { useMemo, useState, useEffect } from 'react';

import { get } from 'lodash';
import { useRequest, useSetState } from 'ahooks';
import ProductSelect from '../payment-link/product-select';
import { useProductsContext } from '../../contexts/products';
import CurrencySelect from './currency-select';
import { getProductByPriceId } from '../../libs/util';
import InfoCard from '../info-card';

export type Price = Omit<InferFormType<TPriceExpanded>, 'product_id' | 'object'> & {
  model: LiteralUnion<'standard' | 'package' | 'graduated' | 'volume' | 'custom' | 'credit_metered', string>;
  recurring: Omit<PriceRecurring, 'usage_type'> & {
    interval_config: string;
  };
  pricing_type?: 'fixed' | 'dynamic';
  base_currency?: string;
  base_amount?: string;
};

export const DEFAULT_PRICE: Omit<Price, 'product' | 'currency' | 'quantity_sold'> = {
  locked: false,
  model: 'standard',
  billing_scheme: '',
  currency_id: '',
  nickname: '',
  type: 'recurring',
  unit_amount: '0',
  lookup_key: '',
  recurring: {
    interval_config: 'month_1',
    interval: 'month',
    interval_count: 1,
    usage_type: 'licensed',
    aggregate_usage: 'sum',
  },
  transform_quantity: {
    divide_by: 1,
    round: 'up',
  },
  tiers: [],
  metadata: {} as any,
  custom_unit_amount: null,
  currency_options: [],
  tiers_mode: null,
  quantity_available: 0,
  quantity_limit_per_checkout: 0,
  pricing_type: 'fixed',
  base_currency: 'USD',
  base_amount: '0',
  dynamic_pricing_config: null,
};

type PriceFormProps = {
  prefix?: string;
  simple?: boolean;
  meterId?: string;
  productType?: string;
};

const INPUT_WIDTH = '100%';

const hasMoreCurrency = (methods: TPaymentMethodExpanded[] = []) => {
  return methods.every((method) => method.payment_currencies.length > 1) || methods.length > 1;
};

const fetchMeters = (): Promise<{ list: TMeterExpanded[]; count: number }> => {
  return api.get('/api/meters?status=active&limit=100').then((res: any) => res.data);
};

export default function PriceForm({ prefix = '', simple = false, productType = undefined }: PriceFormProps) {
  const getFieldName = (name: string) => (prefix ? `${prefix}.${name}` : name);

  const { t, locale } = useLocaleContext();
  const {
    control,
    setValue,
    formState: { errors },
    trigger,
  } = useFormContext();
  const getFieldError = (name: string) => {
    const names = name?.split('.');
    return names.reduce((prev, curr) => prev?.[curr], errors as any);
  };
  const { settings, livemode } = usePaymentContext();
  const currencies = useFieldArray({ control, name: getFieldName('currency_options') });
  const formProductType = useWatch({ control, name: 'type' });
  const currentProductType = productType || formProductType;
  const priceLocked = useWatch({ control, name: getFieldName('locked') });
  const isRecurring = useWatch({ control, name: getFieldName('type') }) === 'recurring';
  const isMetered = useWatch({ control, name: getFieldName('recurring.usage_type') }) === 'metered';
  const isCustomInterval = useWatch({ control, name: getFieldName('recurring.interval_config') }) === 'month_2';
  const model = useWatch({ control, name: getFieldName('model') });
  const intervalSelectValue = useWatch({ control, name: getFieldName('recurring.interval') });
  const defaultCurrencyId = useWatch({ control, name: getFieldName('currency_id') });
  const pricingType = useWatch({ control, name: getFieldName('pricing_type') });
  const baseAmount = useWatch({ control, name: getFieldName('base_amount') });
  const unitAmount = useWatch({ control, name: getFieldName('unit_amount') });
  const currencyOptions = useWatch({ control, name: getFieldName('currency_options') });
  const creditCurrencies = useMemo(() => {
    return settings.paymentMethods.flatMap((method: TPaymentMethodExpanded) =>
      method.payment_currencies.filter((c: TPaymentCurrency) => c.type === 'credit')
    );
  }, [settings.paymentMethods]);
  const { products } = useProductsContext();
  const quantityPositive = (v: number | undefined) => !v || v.toString().match(/^(0|[1-9]\d*)$/);
  const intervalCountPositive = (v: number) => Number.isInteger(Number(v)) && v > 0;

  const meteringMeterId = useWatch({ control, name: getFieldName('recurring.meter_id') });
  const [meters, setMeters] = useState<TMeterExpanded[]>([]);

  // Exchange rate validation state for each currency option
  const [currencyRateValidation, setCurrencyRateValidation] = useSetState<
    Record<
      string,
      {
        validating: boolean;
        valid: boolean;
        error: string | null;
        rate?: string;
      }
    >
  >({});
  const [suggestedApplied, setSuggestedApplied] = useSetState<Record<string, boolean>>({});
  // Track which amount input is focused (by currency ID)
  const [amountInputFocused, setAmountInputFocused] = useSetState<Record<string, boolean>>({});

  const shouldShowRateInfo = pricingType === 'dynamic';

  // Validate exchange rate for a specific currency
  const validateCurrencyRate = async (currencyId: string) => {
    if (!shouldShowRateInfo) {
      return;
    }

    const currency = findCurrency(settings.paymentMethods, currencyId);
    if (!currency) {
      return;
    }

    if (currency.type === 'credit' || currency.paymentMethod?.type === 'stripe') {
      setCurrencyRateValidation({
        [currencyId]: {
          validating: false,
          valid: false,
          error: null,
        },
      });
      return;
    }

    setCurrencyRateValidation({
      [currencyId]: {
        validating: true,
        valid: false,
        error: null,
      },
    });

    try {
      const res: any = await api.post('/api/exchange-rates/validate', { currency: currency.id });
      setCurrencyRateValidation({
        [currencyId]: {
          validating: false,
          valid: res.data.supported,
          error: null,
          rate: res.data.rate,
        },
      });
    } catch (err: any) {
      setCurrencyRateValidation({
        [currencyId]: {
          validating: false,
          valid: false,
          error: t('admin.price.dynamicPricing.validation.error'),
        },
      });
    }
  };

  // Note: Exchange rate validation is now triggered only when amount input is focused
  // to avoid showing rate info automatically when editing a price

  useEffect(() => {
    if (model === 'package' && pricingType === 'dynamic') {
      setValue(getFieldName('pricing_type'), 'fixed', { shouldValidate: true });
    }
  }, [model, pricingType, setValue]);

  const { loading: loadingMeters } = useRequest(
    () => {
      if (model === 'credit_metered') {
        return fetchMeters();
      }
      return Promise.resolve({ list: [] as any, count: 0 });
    },
    {
      refreshDeps: [model],
      onSuccess: (result) => {
        setMeters(result.list);
      },
    }
  );

  const getMeterDisplayName = (meter: TMeter) => {
    return `${meter.name} (${meter.event_name} • ${meter.unit})`;
  };

  const isLocked = priceLocked && window.blocklet?.PAYMENT_CHANGE_LOCKED_PRICE !== '1';

  const validateAmount = (v: number, currency: { maximum_precision?: number }) => {
    if (Number(v) <= 0) {
      return t('admin.price.unit_amount.positive');
    }
    const validPrecision = formatAmountPrecisionLimit(v.toString(), locale, currency?.maximum_precision || 6);
    if (validPrecision) {
      return validPrecision;
    }
    return true;
  };

  const buildSuggestedAmount = (rate?: string) => {
    if (!baseAmount || !rate) return null;
    const base = Number(baseAmount);
    const rateValue = Number(rate);
    if (!Number.isFinite(base) || !Number.isFinite(rateValue) || base <= 0 || rateValue <= 0) {
      return null;
    }
    const rawAmount = base / rateValue;
    if (rawAmount < 0.01) {
      return rawAmount.toFixed(6).replace(/\.?0+$/, '');
    }
    return formatNumber(rawAmount, 2);
  };

  const applySuggestedAmount = (currencyId: string | undefined, amount: string) => {
    if (isLocked || !currencyId) return;
    if (currencyId === defaultCurrencyId) {
      setValue(getFieldName('unit_amount'), amount, { shouldValidate: true });
    }
    const index = currencies.fields.findIndex((x: any) => x.currency_id === currencyId);
    if (index > -1) {
      setValue(getFieldName(`currency_options.${index}.unit_amount`), amount, { shouldValidate: true });
    }
    setSuggestedApplied({ [currencyId]: true });
  };

  const handleRemoveCurrency = async (index: number) => {
    await currencies.remove(index);
    trigger(getFieldName('recurring.interval_config'));
  };

  const handleCurrencyChange = (index: number, currencyId: string) => {
    const update = {
      currency_id: currencyId,
    };
    // @ts-ignore
    if (currencies?.fields?.[index]?.currency) {
      // @ts-ignore
      update.currency = findCurrency(settings.paymentMethods, currencyId);
    }
    currencies.update(index, {
      ...currencies.fields[index],
      ...update,
    });
  };

  const selectedMeter = meters.find((m) => m.id === meteringMeterId);
  const isCreditBilling = model === 'credit_metered';
  const isCreditMode = currentProductType === 'credit';
  const defaultCurrencySymbol = findCurrency(settings.paymentMethods, defaultCurrencyId)?.symbol || '';
  const defaultSuggestedAmount = buildSuggestedAmount(currencyRateValidation[defaultCurrencyId]?.rate);

  return (
    <Root direction="column" alignItems="flex-start" spacing={2}>
      {isLocked && <Alert severity="info">{t('admin.price.locked')}</Alert>}
      <Controller
        name={getFieldName('type')}
        control={control}
        disabled={isLocked}
        render={({ field }) => (
          <Box sx={{ width: INPUT_WIDTH }}>
            <ToggleButtonGroup
              {...field}
              onChange={(_, value: string) => {
                if (value !== null) {
                  setValue(field.name, value);
                }
                if (value === 'one_time') {
                  setValue(getFieldName('model'), 'standard');
                  setValue(getFieldName('currency_id'), settings.baseCurrency?.id);
                  setValue(getFieldName('recurring.meter_id'), '');
                  setValue(getFieldName('recurring.usage_type'), 'licensed');
                }
              }}
              exclusive
              fullWidth
              sx={{
                height: 'auto',
                '& .MuiToggleButton-root': {
                  flexDirection: 'column',
                  alignItems: 'flex-start',
                  justifyContent: 'flex-start',
                  textAlign: 'left',
                  height: 'auto',
                  py: 1,
                },
              }}>
              <ToggleButton value="recurring">
                <Box>
                  <Typography
                    variant="body2"
                    sx={{
                      fontWeight: 'medium',
                      color: 'text.primary',
                    }}>
                    {t('admin.price.types.recurring')}
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{
                      color: 'text.secondary',
                      mt: 0.5,
                    }}>
                    {t('admin.price.types.recurringDesc')}
                  </Typography>
                </Box>
              </ToggleButton>
              <ToggleButton value="one_time">
                <Box>
                  <Typography
                    variant="body2"
                    sx={{
                      fontWeight: 'medium',
                      color: 'text.primary',
                    }}>
                    {t('admin.price.types.onetime')}
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{
                      color: 'text.secondary',
                      mt: 0.5,
                    }}>
                    {t('admin.price.types.onetimeDesc')}
                  </Typography>
                </Box>
              </ToggleButton>
            </ToggleButtonGroup>
          </Box>
        )}
      />
      <Controller
        name={getFieldName('model')}
        control={control}
        rules={{ required: true }}
        disabled={isLocked}
        render={({ field }) => (
          <Box sx={{ width: INPUT_WIDTH }}>
            <FormLabel>{t('admin.price.model')}</FormLabel>
            <Select
              {...field}
              fullWidth
              size="small"
              onChange={(e) => {
                if (e.target.value === 'standard') {
                  setValue(getFieldName('currency_id'), settings.baseCurrency?.id);
                }
                field.onChange(e.target.value);
                if (e.target.value === 'credit_metered') {
                  setValue(getFieldName('type'), 'recurring');
                  setValue(getFieldName('recurring.usage_type'), 'metered');
                } else {
                  setValue(getFieldName('recurring.usage_type'), 'licensed');
                  setValue(getFieldName('recurring.meter_id'), '');
                }
              }}>
              <MenuItem value="standard">{t('admin.price.models.standard')}</MenuItem>
              <MenuItem value="package">{t('admin.price.models.package')}</MenuItem>
              <MenuItem value="credit_metered" disabled={isCreditMode}>
                {t('admin.price.models.creditMetered')}
              </MenuItem>
              <MenuItem value="graduated" disabled>
                {t('admin.price.models.graduated')}
              </MenuItem>
              <MenuItem value="volume" disabled>
                {t('admin.price.models.volume')}
              </MenuItem>
            </Select>
          </Box>
        )}
      />
      {/* 3. Credit 计量计费专用区域 */}
      {isCreditBilling && (
        <Box sx={{ width: INPUT_WIDTH }}>
          <Alert severity="info" sx={{ mb: 2 }}>
            {t('admin.price.creditMetered.description')}
          </Alert>
          <FormLabel sx={{ color: 'text.primary' }}>
            {t('admin.price.creditMetered.selectMeter')}{' '}
            <Typography component="span" sx={{ color: 'error.main' }}>
              *
            </Typography>
          </FormLabel>
          <Autocomplete
            options={meters}
            getOptionLabel={getMeterDisplayName}
            loading={loadingMeters}
            value={selectedMeter || null}
            disabled={isLocked}
            onChange={(_, meter: TMeterExpanded | null) => {
              setValue(getFieldName('recurring.meter_id'), meter?.id || '');
              if (meter?.paymentCurrency) {
                setValue(getFieldName('currency_id'), meter.paymentCurrency.id);
                setValue(getFieldName('unit_amount'), 1);
              }
            }}
            fullWidth
            renderInput={(params) => (
              <TextField
                {...params}
                required
                error={!meteringMeterId}
                helperText={
                  !meteringMeterId ? t('admin.price.creditMetered.required') : t('admin.price.creditMetered.help')
                }
                size="small"
                slotProps={{
                  input: {
                    ...params.InputProps,
                    endAdornment: (
                      <>
                        {loadingMeters ? <div>{t('common.loading')}</div> : null}
                        {params.InputProps.endAdornment}
                      </>
                    ),
                  },
                }}
              />
            )}
          />
        </Box>
      )}
      {/* Dynamic Pricing Toggle */}
      {!isCreditBilling && model === 'standard' && (
        <Box sx={{ width: INPUT_WIDTH }}>
          <Controller
            name={getFieldName('pricing_type')}
            control={control}
            disabled={isLocked}
            render={({ field }) => (
              <FormControlLabel
                sx={{ alignItems: 'flex-start' }}
                control={
                  <Checkbox
                    checked={field.value === 'dynamic'}
                    {...field}
                    onChange={(_, checked: boolean) => {
                      setValue(field.name, checked ? 'dynamic' : 'fixed');
                    }}
                  />
                }
                label={
                  <Stack>
                    <Typography
                      sx={{
                        color: 'text.primary',
                      }}>
                      {t('admin.price.dynamicPricing.label')}
                    </Typography>
                    <Typography
                      sx={{
                        color: 'text.secondary',
                      }}>
                      {t('admin.price.dynamicPricing.description')}
                    </Typography>
                  </Stack>
                }
              />
            )}
          />
        </Box>
      )}
      {/* Dynamic Pricing Configuration - Base Amount */}
      {pricingType === 'dynamic' && !isCreditBilling && (
        <Box sx={{ width: INPUT_WIDTH }}>
          <FormLabel required>{t('admin.price.dynamicPricing.config.baseAmount.label')}</FormLabel>
          <Controller
            name={getFieldName('base_amount')}
            control={control}
            disabled={isLocked}
            rules={{
              required: t('admin.price.dynamicPricing.config.baseAmount.required'),
              validate: (v) => {
                if (Number(v) <= 0) {
                  return t('admin.price.unit_amount.positive');
                }
                return true;
              },
            }}
            render={({ field }) => (
              <TextField
                {...field}
                type="number"
                size="small"
                fullWidth
                error={!!getFieldError(getFieldName('base_amount'))}
                helperText={getFieldError(getFieldName('base_amount'))?.message}
                slotProps={{
                  input: {
                    endAdornment: (
                      <InputAdornment position="end">
                        <Controller
                          name={getFieldName('base_currency')}
                          control={control}
                          disabled={isLocked}
                          rules={{ required: true }}
                          render={({ field: currencyField }) => (
                            <Select
                              {...currencyField}
                              size="small"
                              sx={{ '.MuiOutlinedInput-notchedOutline': { border: 'none' } }}>
                              <MenuItem value="USD">USD</MenuItem>
                            </Select>
                          )}
                        />
                      </InputAdornment>
                    ),
                  },
                  htmlInput: {
                    min: 0,
                    step: 0.01,
                  },
                }}
              />
            )}
          />
          <Typography
            variant="caption"
            sx={{
              color: 'text.secondary',
              display: 'block',
              mt: 0.5,
            }}>
            {t('admin.price.dynamicPricing.config.baseAmount.description')}
          </Typography>
        </Box>
      )}
      {!isCreditBilling && (
        <Stack spacing={2} sx={{ width: INPUT_WIDTH }}>
          <FormLabel tooltip={t('admin.price.amountTip')} description={t('admin.price.amountDescription')}>
            {t('admin.price.amount')}
          </FormLabel>
          <Stack
            direction={{ xs: 'column', sm: 'row' }}
            spacing={2}
            alignItems="flex-start"
            sx={{ width: INPUT_WIDTH, '&': { flexWrap: { xs: 'nowrap', sm: 'wrap' } } }}>
            <Box sx={{ flex: 1, minWidth: { xs: 'auto', sm: '300px' } }}>
              <Controller
                name={getFieldName('unit_amount')}
                control={control}
                rules={{
                  required: t('admin.price.unit_amount.required'),
                  validate: (v) => {
                    const currency = findCurrency(settings.paymentMethods, defaultCurrencyId);
                    return validateAmount(v, currency ?? {});
                  },
                }}
                disabled={isLocked}
                render={({ field }) => (
                  <TextField
                    {...field}
                    type="number"
                    size="small"
                    fullWidth
                    error={!!getFieldError(getFieldName('unit_amount'))}
                    helperText={getFieldError(getFieldName('unit_amount'))?.message}
                    slotProps={{
                      input: {
                        endAdornment: (
                          <InputAdornment position="end">
                            <CurrencySelect
                              mode="selected"
                              hasSelected={(currency) =>
                                currencies.fields.some((x: any) => x.currency_id === currency.id) ||
                                currency.id === defaultCurrencyId
                              }
                              currencyFilter={(c) => c.type !== 'credit'}
                              onSelect={(currencyId) => {
                                const index = currencies.fields.findIndex(
                                  (x: any) => x.currency_id === defaultCurrencyId
                                );
                                if (index > -1) {
                                  // @ts-ignore
                                  handleCurrencyChange(index, currencyId);
                                }
                                setValue(getFieldName('currency'), findCurrency(settings.paymentMethods, currencyId), {
                                  shouldValidate: true,
                                });
                                setValue(getFieldName('currency_id'), currencyId, { shouldValidate: true });

                                if (shouldShowRateInfo) {
                                  validateCurrencyRate(currencyId);
                                }
                              }}
                              value={defaultCurrencyId}
                              disabled={isLocked}
                              selectSX={{ '.MuiOutlinedInput-notchedOutline': { border: 'none' } }}
                            />
                          </InputAdornment>
                        ),
                      },
                    }}
                    onFocus={() => {
                      if (defaultCurrencyId) {
                        setAmountInputFocused({ [defaultCurrencyId]: true });
                        if (shouldShowRateInfo) {
                          validateCurrencyRate(defaultCurrencyId);
                        }
                      }
                    }}
                    onBlur={() => {
                      if (defaultCurrencyId) {
                        setAmountInputFocused({ [defaultCurrencyId]: false });
                      }
                    }}
                    onChange={(e) => {
                      const { value } = e.target;
                      field.onChange(value);
                      if (defaultCurrencyId) {
                        setSuggestedApplied({ [defaultCurrencyId]: false });
                      }
                      const index = currencies.fields.findIndex((x: any) => x.currency_id === defaultCurrencyId);
                      if (index === -1) {
                        return;
                      }
                      setValue(getFieldName(`currency_options.${index}.unit_amount`), value, {
                        shouldValidate: true,
                      });
                    }}
                  />
                )}
              />
              {shouldShowRateInfo && !isLocked && currencyRateValidation[defaultCurrencyId] && (
                <MuiCollapse in={amountInputFocused[defaultCurrencyId]} timeout={200}>
                  {currencyRateValidation[defaultCurrencyId].validating && (
                    <Alert severity="info" sx={{ mt: 1 }}>
                      {t('admin.price.dynamicPricing.validation.checking')}
                    </Alert>
                  )}
                  {!currencyRateValidation[defaultCurrencyId].validating &&
                    currencyRateValidation[defaultCurrencyId].valid && (
                      <Alert severity="success" sx={{ mt: 1 }}>
                        <Stack spacing={0.5}>
                          <Typography variant="body2">
                            {t('admin.price.dynamicPricing.validation.rateLine', {
                              currency: defaultCurrencySymbol,
                              rate: formatNumber(currencyRateValidation[defaultCurrencyId].rate || '0', 2),
                            })}
                          </Typography>
                          {Number(unitAmount) > 0 && currencyRateValidation[defaultCurrencyId]?.rate && (
                            <Typography variant="body2" color="text.secondary">
                              {t('admin.price.dynamicPricing.validation.usdLine', {
                                amount: formatNumber(
                                  Number(unitAmount) * Number(currencyRateValidation[defaultCurrencyId].rate),
                                  2
                                ),
                              })}
                            </Typography>
                          )}
                          {Number(unitAmount) <= 0 &&
                            defaultSuggestedAmount &&
                            !suggestedApplied[defaultCurrencyId] && (
                              <Stack direction="row" spacing={1} alignItems="center">
                                <Typography variant="body2" color="text.secondary">
                                  {t('admin.price.dynamicPricing.validation.estimatedLine', {
                                    amount: defaultSuggestedAmount,
                                    currency: defaultCurrencySymbol,
                                  })}
                                </Typography>
                                <Button
                                  size="small"
                                  variant="text"
                                  sx={{ minWidth: 'auto', px: 0.5 }}
                                  onMouseDown={(e) => e.preventDefault()}
                                  onClick={() => applySuggestedAmount(defaultCurrencyId, defaultSuggestedAmount)}>
                                  {t('admin.price.dynamicPricing.validation.useAmount')}
                                </Button>
                              </Stack>
                            )}
                        </Stack>
                      </Alert>
                    )}
                  {!currencyRateValidation[defaultCurrencyId].validating &&
                    currencyRateValidation[defaultCurrencyId].error && (
                      <Alert severity="error" sx={{ mt: 1 }}>
                        {currencyRateValidation[defaultCurrencyId].error}
                      </Alert>
                    )}
                </MuiCollapse>
              )}
              {hasMoreCurrency(settings.paymentMethods) &&
                currencies.fields.filter((x: any) => x.currency_id !== defaultCurrencyId).length > 0 && (
                  <Stack spacing={1.5} sx={{ width: INPUT_WIDTH, mt: 1.5 }}>
                    {currencies.fields.map((item: any, index: number) => {
                      if (item.currency_id === defaultCurrencyId) {
                        return null;
                      }
                      const fieldName = getFieldName(`currency_options.${index}.unit_amount`);
                      const currency = findCurrency(settings.paymentMethods, item.currency_id);
                      const suggestedAmount = buildSuggestedAmount(currencyRateValidation[item.currency_id]?.rate);
                      return (
                        <Stack
                          key={item.currency_id}
                          direction="row"
                          spacing={1}
                          sx={{
                            alignItems: 'start',
                          }}>
                          <Box sx={{ flex: 1 }}>
                            <Controller
                              name={fieldName}
                              control={control}
                              rules={{
                                required: t('admin.price.unit_amount.required'),
                                validate: (v) => {
                                  return validateAmount(v, currency ?? {});
                                },
                              }}
                              disabled={isLocked}
                              render={({ field }) => (
                                <TextField
                                  {...field}
                                  type="number"
                                  size="small"
                                  fullWidth
                                  sx={{ minWidth: '300px' }}
                                  error={!!getFieldError(fieldName)}
                                  helperText={getFieldError(fieldName)?.message as string}
                                  onFocus={() => {
                                    setAmountInputFocused({ [item.currency_id]: true });
                                    if (shouldShowRateInfo) {
                                      validateCurrencyRate(item.currency_id);
                                    }
                                  }}
                                  onBlur={() => {
                                    setAmountInputFocused({ [item.currency_id]: false });
                                  }}
                                  onChange={(e) => {
                                    const { value } = e.target;
                                    field.onChange(value);
                                    setSuggestedApplied({ [item.currency_id]: false });
                                  }}
                                  slotProps={{
                                    input: {
                                      endAdornment: (
                                        <InputAdornment position="end">
                                          <CurrencySelect
                                            mode="selected"
                                            hasSelected={(c) =>
                                              currencies.fields.some((x: any) => x.currency_id === c.id) ||
                                              c.id === defaultCurrencyId
                                            }
                                            currencyFilter={(c) => c.type !== 'credit'}
                                            onSelect={(currencyId) => {
                                              const cIndex = currencies.fields.findIndex(
                                                (x: any) => x.currency_id === currency?.id
                                              );
                                              if (cIndex > -1) {
                                                // @ts-ignore
                                                handleCurrencyChange(cIndex, currencyId);
                                              }

                                              if (shouldShowRateInfo) {
                                                validateCurrencyRate(currencyId);
                                              }
                                            }}
                                            value={currency?.id!}
                                            disabled={isLocked}
                                            selectSX={{ '.MuiOutlinedInput-notchedOutline': { border: 'none' } }}
                                          />
                                        </InputAdornment>
                                      ),
                                    },
                                  }}
                                />
                              )}
                            />
                            {shouldShowRateInfo && !isLocked && currencyRateValidation[item.currency_id] && (
                              <MuiCollapse in={amountInputFocused[item.currency_id]} timeout={200}>
                                {currencyRateValidation[item.currency_id]?.validating && (
                                  <Alert severity="info" sx={{ mt: 0.5, fontSize: '0.75rem' }}>
                                    {t('admin.price.dynamicPricing.validation.checking')}
                                  </Alert>
                                )}
                                {!currencyRateValidation[item.currency_id]?.validating &&
                                  currencyRateValidation[item.currency_id]?.valid && (
                                    <Alert severity="success" sx={{ mt: 0.5, fontSize: '0.75rem' }}>
                                      <Stack spacing={0.5}>
                                        <Typography variant="body2">
                                          {t('admin.price.dynamicPricing.validation.rateLine', {
                                            currency: currency?.symbol || '',
                                            rate: formatNumber(
                                              currencyRateValidation[item.currency_id]?.rate || '0',
                                              2
                                            ),
                                          })}
                                        </Typography>
                                        {Number(currencyOptions?.[index]?.unit_amount) > 0 &&
                                          currencyRateValidation[item.currency_id]?.rate && (
                                            <Typography variant="body2" color="text.secondary">
                                              {t('admin.price.dynamicPricing.validation.usdLine', {
                                                amount: formatNumber(
                                                  Number(currencyOptions?.[index]?.unit_amount) *
                                                    Number(currencyRateValidation[item.currency_id]?.rate),
                                                  2
                                                ),
                                              })}
                                            </Typography>
                                          )}
                                        {Number(currencyOptions?.[index]?.unit_amount) <= 0 &&
                                          suggestedAmount &&
                                          !suggestedApplied[item.currency_id] && (
                                            <Stack direction="row" spacing={1} alignItems="center">
                                              <Typography variant="body2" color="text.secondary">
                                                {t('admin.price.dynamicPricing.validation.estimatedLine', {
                                                  amount: suggestedAmount,
                                                  currency: currency?.symbol || '',
                                                })}
                                              </Typography>
                                              <Button
                                                size="small"
                                                variant="text"
                                                sx={{ minWidth: 'auto', px: 0.5 }}
                                                onMouseDown={(e) => e.preventDefault()}
                                                onClick={() => applySuggestedAmount(item.currency_id, suggestedAmount)}>
                                                {t('admin.price.dynamicPricing.validation.useAmount')}
                                              </Button>
                                            </Stack>
                                          )}
                                      </Stack>
                                    </Alert>
                                  )}
                                {!currencyRateValidation[item.currency_id]?.validating &&
                                  currencyRateValidation[item.currency_id]?.error && (
                                    <Alert severity="error" sx={{ mt: 0.5, fontSize: '0.75rem' }}>
                                      {currencyRateValidation[item.currency_id]?.error}
                                    </Alert>
                                  )}
                              </MuiCollapse>
                            )}
                          </Box>
                          {!isLocked && (
                            <IconButton
                              size="small"
                              disabled={isLocked}
                              onClick={() => handleRemoveCurrency(index)}
                              sx={{ mt: 0.5, ml: -1 }}>
                              <DeleteOutlineOutlined color="error" sx={{ opacity: 0.75 }} />
                            </IconButton>
                          )}
                        </Stack>
                      );
                    })}
                  </Stack>
                )}
              {!isLocked && hasMoreCurrency(settings.paymentMethods) && !isCreditBilling && (
                <Box sx={{ width: INPUT_WIDTH, mt: 1.5 }}>
                  <CurrencySelect
                    mode="waiting"
                    hasSelected={(currency) =>
                      currencies.fields.some((x: any) => x.currency_id === currency.id) ||
                      currency.id === defaultCurrencyId
                    }
                    currencyFilter={(c) => c.type !== 'credit'}
                    onSelect={(currencyId) => {
                      currencies.append({ currency_id: currencyId, unit_amount: 0 });

                      if (shouldShowRateInfo) {
                        validateCurrencyRate(currencyId);
                      }
                    }}
                    value=""
                    width="100%"
                  />
                </Box>
              )}
            </Box>
            {model === 'package' && (
              <Box sx={{ flex: { xs: 'none', sm: 1 }, width: { xs: '100%', sm: 'auto' } }}>
                <Controller
                  name={getFieldName('transform_quantity.divide_by')}
                  control={control}
                  disabled={isLocked}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      type="number"
                      size="small"
                      fullWidth
                      slotProps={{
                        input: {
                          startAdornment: <InputAdornment position="start">{t('common.per')}</InputAdornment>,
                          endAdornment: <InputAdornment position="end">{t('common.unit')}</InputAdornment>,
                        },
                      }}
                    />
                  )}
                />
              </Box>
            )}
          </Stack>
        </Stack>
      )}
      {/* 周期性配置 */}
      {isRecurring && (
        <Stack direction="row" spacing={2} sx={{ width: INPUT_WIDTH }}>
          <Box sx={{ flex: 1 }}>
            <FormLabel>{t('admin.price.recurring.interval')}</FormLabel>
            <Controller
              name={getFieldName('recurring.interval_config')}
              control={control}
              disabled={isLocked}
              rules={{
                validate: (val) => {
                  const hasStripe = currencies.fields?.some((x: any) => {
                    return !!settings.paymentMethods.find(
                      (y: TPaymentMethodExpanded) => y?.type === 'stripe' && x?.currency_id === y?.default_currency_id
                    );
                  });
                  if (val === 'hour_1' && hasStripe) {
                    return t('admin.price.recurring.stripeTip');
                  }
                  return true;
                },
              }}
              render={({ field }) => (
                <Select
                  {...field}
                  value={field.value || 'month_1'}
                  onChange={(e) => {
                    const [interval, count] = e.target.value.split('_');
                    setValue(getFieldName('recurring.interval'), interval);
                    setValue(getFieldName('recurring.interval_count'), +count);
                    setValue(getFieldName('recurring.interval_config'), e.target.value);
                    trigger(getFieldName('recurring.interval_config'));
                  }}
                  fullWidth
                  error={!!get(errors, getFieldName('recurring.interval_config'))}
                  size="small">
                  {!livemode && <MenuItem value="hour_1">{t('common.hourly')}</MenuItem>}
                  <MenuItem value="day_1">{t('common.daily')}</MenuItem>
                  <MenuItem value="week_1">{t('common.weekly')}</MenuItem>
                  <MenuItem value="month_1">{t('common.monthly')}</MenuItem>
                  <MenuItem value="month_3">{t('common.month3')}</MenuItem>
                  <MenuItem value="month_6">{t('common.month6')}</MenuItem>
                  <MenuItem value="year_1">{t('common.yearly')}</MenuItem>
                  <MenuItem value="month_2">{t('common.custom')}</MenuItem>
                </Select>
              )}
            />
            {get(errors, getFieldName('recurring.interval_config'))?.message && (
              <Typography color="error" sx={{ fontSize: '0.75rem', mt: 0.5 }}>
                {/* @ts-ignore */}
                {get(errors, getFieldName('recurring.interval_config')).message}
              </Typography>
            )}
          </Box>

          {/* 自定义间隔 */}
          {isCustomInterval && (
            <Box sx={{ flex: 1 }}>
              <FormLabel sx={{ visibility: 'hidden' }}>placeholder</FormLabel>
              <Controller
                name={getFieldName('recurring.interval_count')}
                control={control}
                disabled={isLocked}
                rules={{
                  validate: (v) => {
                    if (!intervalCountPositive(v)) {
                      return t('admin.price.recurring.intervalCountTip');
                    }
                    return true;
                  },
                }}
                render={({ field }) => (
                  <TextField
                    {...field}
                    type="number"
                    size="small"
                    fullWidth
                    error={!!get(errors, getFieldName('recurring.interval_count'))}
                    helperText={get(errors, getFieldName('recurring.interval_count'))?.message as string}
                    slotProps={{
                      input: {
                        startAdornment: <InputAdornment position="start">{t('common.every')}</InputAdornment>,
                        endAdornment: (
                          <InputAdornment position="end">
                            <select
                              onChange={(e) => setValue(getFieldName('recurring.interval'), e.target.value)}
                              value={intervalSelectValue}
                              style={{ background: 'none', outline: 'none' }}>
                              <option value="day">{t('common.days')}</option>
                              <option value="week">{t('common.weeks')}</option>
                              <option value="month">{t('common.months')}</option>
                              <option value="year">{t('common.years')}</option>
                            </select>
                          </InputAdornment>
                        ),
                      },
                    }}
                  />
                )}
              />
            </Box>
          )}
        </Stack>
      )}
      {isRecurring && !isCreditMode && !isCreditBilling && (
        <Box sx={{ width: INPUT_WIDTH }}>
          <Controller
            name={getFieldName('recurring.usage_type')}
            control={control}
            disabled={isLocked}
            render={({ field }) => (
              <FormControlLabel
                sx={{ alignItems: 'flex-start' }}
                control={
                  <Checkbox
                    checked={field.value === 'metered'}
                    {...field}
                    onChange={(_, checked: boolean) => setValue(field.name, checked ? 'metered' : 'licensed')}
                  />
                }
                label={
                  <Stack>
                    <Typography
                      sx={{
                        color: 'text.primary',
                      }}>
                      {t('admin.price.recurring.metered')}
                    </Typography>
                    <Typography
                      sx={{
                        color: 'text.secondary',
                        maxWidth: '80%',
                      }}>
                      {t('admin.price.recurring.meteredTip')}
                    </Typography>
                  </Stack>
                }
              />
            )}
          />
        </Box>
      )}
      {/* 聚合方式选择 - 仅在按量计费时显示 */}
      {isRecurring && isMetered && !isCreditBilling && (
        <Box sx={{ width: INPUT_WIDTH }}>
          <FormLabel>{t('admin.price.recurring.aggregate')}</FormLabel>
          <Controller
            name={getFieldName('recurring.aggregate_usage')}
            control={control}
            disabled={isLocked}
            render={({ field }) => (
              <Select {...field} fullWidth size="small">
                <MenuItem value="sum">{t('admin.price.aggregate.sum')}</MenuItem>
                <MenuItem value="max">{t('admin.price.aggregate.max')}</MenuItem>
                <MenuItem value="last_ever">{t('admin.price.aggregate.last_ever')}</MenuItem>
                <MenuItem value="last_during_period">{t('admin.price.aggregate.last_during_period')}</MenuItem>
              </Select>
            )}
          />
        </Box>
      )}
      {/* Credit 模式的特殊配置 */}
      {isCreditMode && (
        <>
          <Divider sx={{ width: '100%' }} />
          <Collapse
            trigger={
              <Typography sx={{ fontWeight: 500 }}>
                {t('admin.creditProduct.settings')}
                <Typography component="span" color="error" sx={{ ml: 0.5 }}>
                  *
                </Typography>
              </Typography>
            }
            expanded={isLocked}
            style={{ width: INPUT_WIDTH }}>
            <Box sx={{ width: INPUT_WIDTH, mb: 2, pl: 2, pr: 1 }}>
              {/* 发放模式选择 - 仅对订阅类型显示 */}
              {isRecurring && (
                <Controller
                  name={getFieldName('metadata')}
                  control={control}
                  render={({ field }) => {
                    const deliveryMode = field.value?.credit_config?.schedule?.enabled ? 'periodic' : 'once';
                    return (
                      <Box sx={{ width: '100%', mb: 2 }}>
                        <FormLabel>{t('admin.creditProduct.deliveryMode.label')}</FormLabel>
                        <ToggleButtonGroup
                          value={deliveryMode}
                          exclusive
                          fullWidth
                          size="small"
                          onChange={(_, newMode) => {
                            if (!newMode) return;
                            const metadata = field.value || {};
                            const creditConfig = metadata.credit_config || {};
                            if (newMode === 'periodic') {
                              creditConfig.schedule = {
                                enabled: true,
                                delivery_mode: 'schedule',
                                interval_value: 1,
                                interval_unit: 'day',
                                first_grant_timing: 'immediate',
                                expire_with_next_grant: true,
                              };
                              // Clear one-time fields
                              delete creditConfig.credit_amount;
                              delete creditConfig.valid_duration_value;
                              delete creditConfig.valid_duration_unit;
                            } else {
                              delete creditConfig.schedule;
                            }
                            metadata.credit_config = creditConfig;
                            field.onChange(metadata);
                          }}>
                          <ToggleButton value="once">{t('admin.creditProduct.deliveryMode.once')}</ToggleButton>
                          <ToggleButton value="periodic">{t('admin.creditProduct.deliveryMode.periodic')}</ToggleButton>
                        </ToggleButtonGroup>
                      </Box>
                    );
                  }}
                />
              )}

              {/* 一次性发放配置 */}
              <Controller
                name={getFieldName('metadata')}
                control={control}
                render={({ field }) => {
                  const isPeriodicMode = isRecurring && field.value?.credit_config?.schedule?.enabled;
                  if (isPeriodicMode) return <Box />;

                  return (
                    <>
                      {/* Credit 数量配置 */}
                      <Box sx={{ width: '100%', mb: 2 }}>
                        <FormLabel required>{t('admin.creditProduct.creditAmount.label')}</FormLabel>
                        <TextField
                          size="small"
                          fullWidth
                          type="number"
                          placeholder={t('admin.creditProduct.creditAmount.placeholder')}
                          value={field.value?.credit_config?.credit_amount || ''}
                          disabled={isLocked}
                          onChange={(e) => {
                            const metadata = field.value || {};
                            const creditConfig = metadata.credit_config || {};
                            if (e.target.value) {
                              creditConfig.credit_amount = e.target.value;
                            } else {
                              delete creditConfig.credit_amount;
                            }
                            metadata.credit_config = creditConfig;
                            field.onChange(metadata);
                          }}
                          slotProps={{
                            input: {
                              endAdornment: (
                                <InputAdornment position="end">
                                  <CurrencySelect
                                    mode="selected"
                                    hasSelected={(c) => currencies.fields.some((x: any) => x.currency_id === c.id)}
                                    currencyFilter={(c) => c.type === 'credit'}
                                    onSelect={(currencyId) => {
                                      const metadata = field.value || {};
                                      const creditConfig = metadata.credit_config || {};
                                      creditConfig.currency_id = currencyId;
                                      metadata.credit_config = creditConfig;
                                      field.onChange(metadata);
                                    }}
                                    value={field.value?.credit_config?.currency_id || creditCurrencies?.[0]?.id}
                                    disabled={isLocked}
                                    hideMethod
                                    selectSX={{ '.MuiOutlinedInput-notchedOutline': { border: 'none' } }}
                                  />
                                </InputAdornment>
                              ),
                            },
                            htmlInput: {
                              min: 0,
                              step: 'any',
                            },
                          }}
                        />
                        <Typography
                          variant="caption"
                          sx={{
                            color: 'text.secondary',
                            display: 'block',
                            mt: 0.5,
                          }}>
                          {t('admin.creditProduct.creditAmount.description')}
                        </Typography>
                      </Box>

                      {/* 可用时长配置 */}
                      <Box sx={{ width: '100%', mb: 2 }}>
                        <FormLabel tooltip={t('admin.creditProduct.validDuration.help')}>
                          {t('admin.creditProduct.validDuration.label')}
                        </FormLabel>
                        <Stack
                          direction="row"
                          spacing={1}
                          sx={{
                            alignItems: 'center',
                          }}>
                          <TextField
                            size="small"
                            type="number"
                            sx={{ flex: 1 }}
                            value={field.value?.credit_config?.valid_duration_value ?? '0'}
                            placeholder="0"
                            disabled={isLocked}
                            onChange={(e) => {
                              const metadata = field.value || {};
                              const creditConfig = metadata.credit_config || {};
                              const value = +e.target.value;
                              if (!Number.isNaN(value) && value >= 0) {
                                creditConfig.valid_duration_value = +value;
                              } else {
                                delete creditConfig.valid_duration_value;
                              }
                              metadata.credit_config = creditConfig;
                              field.onChange(metadata);
                            }}
                            slotProps={{
                              htmlInput: {
                                min: 0,
                                step: 0.1,
                              },
                            }}
                          />
                          <Select
                            size="small"
                            sx={{ minWidth: 120 }}
                            disabled={isLocked}
                            value={field.value?.credit_config?.valid_duration_unit || 'days'}
                            onChange={(e) => {
                              const metadata = field.value || {};
                              const creditConfig = metadata.credit_config || {};
                              creditConfig.valid_duration_unit = e.target.value;
                              metadata.credit_config = creditConfig;
                              field.onChange(metadata);
                            }}>
                            {!livemode && (
                              <MenuItem value="hours">{t('admin.creditProduct.validDuration.hours')}</MenuItem>
                            )}
                            <MenuItem value="days">{t('admin.creditProduct.validDuration.days')}</MenuItem>
                            <MenuItem value="weeks">{t('admin.creditProduct.validDuration.weeks')}</MenuItem>
                            <MenuItem value="months">{t('admin.creditProduct.validDuration.months')}</MenuItem>
                            <MenuItem value="years">{t('admin.creditProduct.validDuration.years')}</MenuItem>
                          </Select>
                        </Stack>
                        <Typography
                          variant="caption"
                          sx={{
                            color: 'text.secondary',
                            display: 'block',
                            mt: 0.5,
                          }}>
                          {t('admin.creditProduct.validDuration.description')}
                        </Typography>
                      </Box>
                    </>
                  );
                }}
              />

              {/* 周期性发放配置 */}
              {isRecurring && (
                <Controller
                  name={getFieldName('metadata')}
                  control={control}
                  render={({ field }) => {
                    const isPeriodicMode = field.value?.credit_config?.schedule?.enabled;
                    if (!isPeriodicMode) return <Box />;

                    const expireWithNextGrant = field.value?.credit_config?.schedule?.expire_with_next_grant ?? true;

                    return (
                      <Stack spacing={2} sx={{ mb: 2 }}>
                        {/* 发放间隔 */}
                        <Box>
                          <FormLabel>{t('admin.creditProduct.schedule.interval.label')}</FormLabel>
                          <Stack direction="row" spacing={1} alignItems="center">
                            <TextField
                              size="small"
                              type="number"
                              sx={{ flex: 1 }}
                              value={field.value?.credit_config?.schedule?.interval_value || 1}
                              onChange={(e) => {
                                const metadata = field.value || {};
                                const creditConfig = metadata.credit_config || {};
                                const schedule = creditConfig.schedule || {};
                                schedule.interval_value = Math.max(0.01, parseFloat(e.target.value) || 1);
                                creditConfig.schedule = schedule;
                                metadata.credit_config = creditConfig;
                                field.onChange(metadata);
                              }}
                              slotProps={{ htmlInput: { min: 0.01, step: 0.01 } }}
                            />
                            <Select
                              size="small"
                              sx={{ minWidth: 100 }}
                              value={field.value?.credit_config?.schedule?.interval_unit || 'day'}
                              onChange={(e) => {
                                const metadata = field.value || {};
                                const creditConfig = metadata.credit_config || {};
                                const schedule = creditConfig.schedule || {};
                                schedule.interval_unit = e.target.value;
                                creditConfig.schedule = schedule;
                                metadata.credit_config = creditConfig;
                                field.onChange(metadata);
                              }}>
                              {!livemode && (
                                <MenuItem value="hour">{t('admin.creditProduct.schedule.interval.hour')}</MenuItem>
                              )}
                              <MenuItem value="day">{t('admin.creditProduct.schedule.interval.day')}</MenuItem>
                              <MenuItem value="week">{t('admin.creditProduct.schedule.interval.week')}</MenuItem>
                              <MenuItem value="month">{t('admin.creditProduct.schedule.interval.month')}</MenuItem>
                            </Select>
                          </Stack>
                        </Box>

                        {/* 每次发放数量（带货币选择） */}
                        <Box>
                          <FormLabel required>{t('admin.creditProduct.schedule.amountPerGrant.label')}</FormLabel>
                          <TextField
                            size="small"
                            type="number"
                            fullWidth
                            required
                            value={field.value?.credit_config?.schedule?.amount_per_grant || ''}
                            onChange={(e) => {
                              const metadata = field.value || {};
                              const creditConfig = metadata.credit_config || {};
                              const schedule = creditConfig.schedule || {};
                              schedule.amount_per_grant = e.target.value;
                              creditConfig.schedule = schedule;
                              metadata.credit_config = creditConfig;
                              field.onChange(metadata);
                            }}
                            slotProps={{
                              input: {
                                endAdornment: (
                                  <InputAdornment position="end">
                                    <CurrencySelect
                                      mode="selected"
                                      hasSelected={(c) => currencies.fields.some((x: any) => x.currency_id === c.id)}
                                      currencyFilter={(c) => c.type === 'credit'}
                                      onSelect={(currencyId) => {
                                        const metadata = field.value || {};
                                        const creditConfig = metadata.credit_config || {};
                                        creditConfig.currency_id = currencyId;
                                        metadata.credit_config = creditConfig;
                                        field.onChange(metadata);
                                      }}
                                      value={field.value?.credit_config?.currency_id || creditCurrencies?.[0]?.id}
                                      disabled={isLocked}
                                      hideMethod
                                      selectSX={{ '.MuiOutlinedInput-notchedOutline': { border: 'none' } }}
                                    />
                                  </InputAdornment>
                                ),
                              },
                              htmlInput: { min: 0, step: 'any' },
                            }}
                          />
                          <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mt: 0.5 }}>
                            {t('admin.creditProduct.schedule.amountPerGrant.description')}
                          </Typography>
                        </Box>

                        {/* 可用时长配置 */}
                        <Box>
                          <FormLabel tooltip={t('admin.creditProduct.validDuration.help')}>
                            {t('admin.creditProduct.validDuration.label')}
                          </FormLabel>
                          <Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
                            <TextField
                              size="small"
                              type="number"
                              sx={{ flex: 1 }}
                              value={field.value?.credit_config?.valid_duration_value ?? '0'}
                              placeholder="0"
                              disabled={isLocked || expireWithNextGrant}
                              onChange={(e) => {
                                const metadata = field.value || {};
                                const creditConfig = metadata.credit_config || {};
                                const value = +e.target.value;
                                if (!Number.isNaN(value) && value >= 0) {
                                  creditConfig.valid_duration_value = +value;
                                } else {
                                  delete creditConfig.valid_duration_value;
                                }
                                metadata.credit_config = creditConfig;
                                field.onChange(metadata);
                              }}
                              slotProps={{ htmlInput: { min: 0, step: 0.1 } }}
                            />
                            <Select
                              size="small"
                              sx={{ minWidth: 120 }}
                              disabled={isLocked || expireWithNextGrant}
                              value={field.value?.credit_config?.valid_duration_unit || 'days'}
                              onChange={(e) => {
                                const metadata = field.value || {};
                                const creditConfig = metadata.credit_config || {};
                                creditConfig.valid_duration_unit = e.target.value;
                                metadata.credit_config = creditConfig;
                                field.onChange(metadata);
                              }}>
                              {!livemode && (
                                <MenuItem value="hours">{t('admin.creditProduct.validDuration.hours')}</MenuItem>
                              )}
                              <MenuItem value="days">{t('admin.creditProduct.validDuration.days')}</MenuItem>
                              <MenuItem value="weeks">{t('admin.creditProduct.validDuration.weeks')}</MenuItem>
                              <MenuItem value="months">{t('admin.creditProduct.validDuration.months')}</MenuItem>
                              <MenuItem value="years">{t('admin.creditProduct.validDuration.years')}</MenuItem>
                            </Select>
                          </Stack>
                          <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mt: 0.5 }}>
                            {t('admin.creditProduct.validDuration.description')}
                          </Typography>
                        </Box>

                        {/* 随下次发放过期 */}
                        <FormControlLabel
                          sx={{ alignItems: 'flex-start' }}
                          control={
                            <Checkbox
                              checked={expireWithNextGrant}
                              onChange={(_, checked) => {
                                const metadata = field.value || {};
                                const creditConfig = metadata.credit_config || {};
                                const schedule = creditConfig.schedule || {};
                                schedule.expire_with_next_grant = checked;
                                creditConfig.schedule = schedule;
                                metadata.credit_config = creditConfig;
                                field.onChange(metadata);
                              }}
                            />
                          }
                          label={
                            <Box>
                              <Typography sx={{ color: 'text.primary' }}>
                                {t('admin.creditProduct.schedule.expireWithNextGrant.label')}
                              </Typography>
                              <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                                {t('admin.creditProduct.schedule.expireWithNextGrant.description')}
                              </Typography>
                            </Box>
                          }
                        />
                      </Stack>
                    );
                  }}
                />
              )}

              {/* 关联特定价格 */}
              <Controller
                name={getFieldName('metadata')}
                control={control}
                render={({ field }) => (
                  <Box sx={{ width: '100%', mb: 2 }}>
                    <FormLabel tooltip={t('admin.creditProduct.associatedPrices.help')}>
                      {t('admin.creditProduct.associatedPrices.label')}
                    </FormLabel>

                    {/* 显示已选择的价格 */}
                    {field.value?.credit_config?.applicable_prices &&
                      Array.isArray(field.value.credit_config.applicable_prices) &&
                      field.value.credit_config.applicable_prices.length > 0 && (
                        <Stack spacing={1} sx={{ mb: 2 }}>
                          {field.value.credit_config.applicable_prices.map((priceId: string) => {
                            const product = getProductByPriceId(products, priceId);
                            if (!product) {
                              return null;
                            }
                            const productCurrency =
                              findCurrency(settings.paymentMethods, product.prices[0]?.currency_id ?? '') ||
                              settings.baseCurrency;

                            return (
                              <Box
                                key={priceId}
                                sx={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'space-between',
                                  p: 1,
                                  border: '1px solid',
                                  borderColor: 'divider',
                                  borderRadius: 1,
                                  backgroundColor: 'background.paper',
                                }}>
                                <InfoCard
                                  logo={product.images[0]}
                                  name={product.name}
                                  description={formatPrice(product.prices[0] as TPrice, productCurrency!)}
                                />
                                <IconButton
                                  size="small"
                                  onClick={() => {
                                    const metadata = field.value || {};
                                    const creditConfig = metadata.credit_config || {};
                                    const currentPrices = creditConfig.applicable_prices || [];
                                    const newPrices = currentPrices.filter((id: string) => id !== priceId);
                                    if (newPrices.length > 0) {
                                      creditConfig.applicable_prices = newPrices;
                                    } else {
                                      delete creditConfig.applicable_prices;
                                    }
                                    metadata.credit_config = creditConfig;
                                    field.onChange(metadata);
                                  }}>
                                  <DeleteOutlineOutlined fontSize="small" />
                                </IconButton>
                              </Box>
                            );
                          })}
                        </Stack>
                      )}

                    {/* 价格选择器 */}
                    <ProductSelect
                      mode="selecting"
                      addProduct={false}
                      filterPrice={(x) => {
                        return isCreditMetered(x) && x.currency_id === field.value?.credit_config?.currency_id;
                      }}
                      hasSelected={(price) => {
                        const selectedPrices = field.value?.credit_config?.applicable_prices || [];
                        return selectedPrices.includes(price.id);
                      }}
                      onSelect={(priceId) => {
                        const metadata = field.value || {};
                        const creditConfig = metadata.credit_config || {};
                        const currentPrices = creditConfig.applicable_prices || [];
                        creditConfig.applicable_prices = [...currentPrices, priceId];
                        metadata.credit_config = creditConfig;
                        field.onChange(metadata);
                      }}
                    />

                    <Typography
                      variant="caption"
                      sx={{
                        color: 'text.secondary',
                        display: 'block',
                        mt: 0.5,
                      }}>
                      {t('admin.creditProduct.associatedPrices.description')}
                    </Typography>
                  </Box>
                )}
              />

              {/* 优先级设置 */}
              <Controller
                name={getFieldName('metadata')}
                control={control}
                disabled={isLocked}
                render={({ field }) => (
                  <Box sx={{ width: '100%' }}>
                    <FormLabel tooltip={t('admin.creditProduct.priority.help')} required>
                      {t('admin.creditProduct.priority.label')}
                    </FormLabel>
                    <TextField
                      size="small"
                      fullWidth
                      type="number"
                      placeholder="50"
                      value={field.value?.credit_config?.priority ?? '50'}
                      onChange={(e) => {
                        const metadata = field.value || {};
                        const creditConfig = metadata.credit_config || {};
                        const value = e.target.value ?? '50';
                        creditConfig.priority = value;
                        metadata.credit_config = creditConfig;
                        field.onChange(metadata);
                      }}
                      slotProps={{
                        htmlInput: {
                          min: 0,
                          max: 100,
                        },
                      }}
                    />
                    <Typography
                      variant="caption"
                      sx={{
                        color: 'text.secondary',
                        display: 'block',
                        mt: 0.5,
                      }}>
                      {t('admin.creditProduct.priority.description')}
                    </Typography>
                  </Box>
                )}
              />
            </Box>
          </Collapse>
        </>
      )}
      {!simple && (
        <>
          <Divider sx={{ width: '100%' }} />
          <Collapse
            trigger={t('admin.price.advanced')}
            expanded={isLocked}
            style={{
              width: INPUT_WIDTH,
              '.MuiCollapse-root': {
                width: '100%',
              },
            }}>
            <Stack
              sx={{
                alignItems: 'flex-start',
                width: INPUT_WIDTH,
                pl: 2,
                pr: 1,
              }}>
              <Controller
                name={getFieldName('quantity_available')}
                control={control}
                render={({ field }) => (
                  <Box sx={{ width: '100%', mb: 2 }}>
                    <FormLabel>{t('admin.price.quantityAvailable.label')}</FormLabel>
                    <TextField
                      {...field}
                      size="small"
                      sx={{ width: INPUT_WIDTH }}
                      type="number"
                      placeholder={t('admin.price.quantityAvailable.placeholder')}
                      error={!quantityPositive(field.value)}
                      helperText={!quantityPositive(field.value) && t('admin.price.quantity.tip')}
                    />
                    <Typography
                      variant="caption"
                      sx={{
                        color: 'text.secondary',
                        display: 'block',
                        mt: 0.5,
                      }}>
                      {t('admin.price.quantityAvailable.description')}
                    </Typography>
                  </Box>
                )}
              />
              <Controller
                name={getFieldName('quantity_limit_per_checkout')}
                control={control}
                render={({ field }) => (
                  <Box sx={{ width: '100%', mb: 2 }}>
                    <FormLabel>{t('admin.price.quantityLimitPerCheckout.label')}</FormLabel>
                    <TextField
                      {...field}
                      size="small"
                      sx={{ width: INPUT_WIDTH }}
                      type="number"
                      fullWidth
                      placeholder={t('admin.price.quantityLimitPerCheckout.placeholder')}
                      error={!quantityPositive(field.value)}
                      helperText={!quantityPositive(field.value) && t('admin.price.quantity.tip')}
                    />
                    <Typography
                      variant="caption"
                      sx={{
                        color: 'text.secondary',
                        display: 'block',
                        mt: 0.5,
                      }}>
                      {t('admin.price.quantityLimitPerCheckout.description')}
                    </Typography>
                  </Box>
                )}
              />
              <Controller
                name={getFieldName('nickname')}
                control={control}
                rules={{
                  maxLength: {
                    value: 64,
                    message: t('common.maxLength', { len: 64 }),
                  },
                }}
                render={({ field }) => (
                  <Box sx={{ width: '100%', mb: 2 }}>
                    <FormLabel>{t('admin.price.nickname.label')}</FormLabel>
                    <TextField
                      {...field}
                      size="small"
                      sx={{ width: INPUT_WIDTH }}
                      slotProps={{
                        htmlInput: {
                          maxLength: 64,
                        },
                      }}
                    />
                  </Box>
                )}
              />
              <Controller
                name={getFieldName('lookup_key')}
                control={control}
                rules={{
                  maxLength: {
                    value: 64,
                    message: t('common.maxLength', { len: 64 }),
                  },
                }}
                render={({ field }) => (
                  <Box sx={{ width: '100%', mb: 2 }}>
                    <FormLabel>{t('admin.price.lookup_key.label')}</FormLabel>
                    <TextField
                      {...field}
                      size="small"
                      sx={{ width: INPUT_WIDTH }}
                      slotProps={{
                        htmlInput: {
                          maxLength: 64,
                        },
                      }}
                    />
                    <Typography
                      variant="caption"
                      sx={{
                        color: 'text.secondary',
                        display: 'block',
                        mt: 0.5,
                      }}>
                      {t('admin.price.lookup_key.description')}
                    </Typography>
                  </Box>
                )}
              />
            </Stack>
          </Collapse>
        </>
      )}
    </Root>
  );
}

const Root = styled(Stack)`
  select {
    border: none;
    &:active,
    &:focus {
      border: none;
    }
  }
`;
