import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { PriceRecurring, TLineItemExpanded, TPaymentCurrency } from '@blocklet/payment-types';
import { Box, Stack, Typography, IconButton, TextField, Alert } from '@mui/material';
import { Add, Remove } from '@mui/icons-material';

import React, { useMemo, useState } from 'react';
import Status from '../components/status';
import Switch from '../components/switch-button';
import {
  findCurrency,
  formatLineItemPricing,
  formatPrice,
  formatQuantityInventory,
  formatRecurring,
  formatUpsellSaving,
} from '../libs/util';
import ProductCard from './product-card';
import dayjs from '../libs/dayjs';
import { usePaymentContext } from '../contexts/payment';

type Props = {
  item: TLineItemExpanded;
  items: TLineItemExpanded[];
  trialInDays: number;
  trialEnd?: number;
  currency: TPaymentCurrency;
  onUpsell: Function;
  onDownsell: Function;
  mode?: 'normal' | 'cross-sell';
  children?: React.ReactNode;
  // 数量调整相关
  adjustableQuantity?: {
    enabled: boolean;
    minimum?: number;
    maximum?: number;
  };
  onQuantityChange?: (itemId: string, quantity: number) => void;
  completed?: boolean;
};

export default function ProductItem({
  item,
  items,
  trialInDays,
  trialEnd = 0,
  currency,
  mode = 'normal',
  children = null,
  onUpsell,
  onDownsell,
  completed = false,
  adjustableQuantity = { enabled: false },
  onQuantityChange = () => {},
}: Props) {
  const { t, locale } = useLocaleContext();
  const { settings } = usePaymentContext();
  const pricing = formatLineItemPricing(item, currency, { trialEnd, trialInDays }, locale);
  const saving = formatUpsellSaving(items, currency);
  const metered = item.price?.recurring?.usage_type === 'metered' ? t('common.metered') : '';
  const canUpsell = mode === 'normal' && items.length === 1;

  const isCreditProduct = item.price.product?.type === 'credit' && item.price.metadata?.credit_config?.credit_amount;
  const creditAmount = isCreditProduct ? Number(item.price.metadata.credit_config.credit_amount) : 0;
  const creditCurrency = isCreditProduct
    ? findCurrency(settings.paymentMethods, item.price.metadata?.credit_config?.currency_id ?? '')
    : null;
  const validDuration = item.price.metadata?.credit_config?.valid_duration_value;
  const validDurationUnit = item.price.metadata?.credit_config?.valid_duration_unit || 'days';

  const [localQuantity, setLocalQuantity] = useState(item.quantity);
  const canAdjustQuantity = adjustableQuantity.enabled && mode === 'normal';
  const minQuantity = Math.max(adjustableQuantity.minimum || 1, 1);
  const quantityAvailable = Math.min(item.price.quantity_limit_per_checkout, item.price.quantity_available);
  const maxQuantity = Math.min(adjustableQuantity.maximum || 999, quantityAvailable || 999);

  const handleQuantityChange = (newQuantity: number) => {
    if (newQuantity >= minQuantity && newQuantity <= maxQuantity) {
      setLocalQuantity(newQuantity);
      if (formatQuantityInventory(item.price, newQuantity, locale)) {
        return;
      }
      onQuantityChange(item.price_id, newQuantity);
    }
  };

  const handleQuantityIncrease = () => {
    if (localQuantity < maxQuantity) {
      handleQuantityChange(localQuantity + 1);
    }
  };

  const handleQuantityDecrease = () => {
    if (localQuantity > minQuantity) {
      handleQuantityChange(localQuantity - 1);
    }
  };

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

  // Credit 信息格式化
  const formatCreditInfo = () => {
    if (!isCreditProduct) return null;

    const isRecurring = item.price.type === 'recurring';
    const totalCredit = creditAmount * localQuantity;

    let message = '';
    if (isRecurring) {
      message = t('payment.checkout.credit.recurringInfo', {
        amount: totalCredit,
        period: formatRecurring(item.price.recurring!, true, 'per', locale),
      });
    } else {
      message = t('payment.checkout.credit.oneTimeInfo', {
        amount: totalCredit,
        symbol: creditCurrency?.symbol || 'Credits',
      });
    }

    if (validDuration && validDuration > 0) {
      message += `，${t('payment.checkout.credit.expiresIn', {
        duration: validDuration,
        unit: t(`common.${validDurationUnit}`),
      })}`;
    }

    return message;
  };

  const primaryText = useMemo(() => {
    const price = item.upsell_price || item.price || {};
    const isRecurring = price?.type === 'recurring' && price?.recurring;
    const trial = trialInDays > 0 || trialEnd > dayjs().unix();
    if (isRecurring && !trial && price?.recurring?.usage_type !== 'metered') {
      return `${pricing.primary} ${price.recurring ? formatRecurring(price.recurring, false, 'slash', locale) : ''}`;
    }
    return pricing.primary;
  }, [trialInDays, trialEnd, pricing, item, locale]);

  const quantityInventoryError = formatQuantityInventory(item.price, localQuantity, locale);

  return (
    <Stack
      direction="column"
      spacing={1}
      className="product-item"
      sx={{
        alignItems: 'flex-start',
        width: '100%',
      }}>
      <Stack
        direction="column"
        className="product-item-content"
        sx={{
          alignItems: 'flex-start',
          width: '100%',
        }}>
        <Stack
          direction="row"
          spacing={0.5}
          sx={{
            alignItems: 'center',
            flexWrap: 'wrap',
            justifyContent: 'space-between',
            width: '100%',
          }}>
          <ProductCard
            logo={item.price.product?.images[0]}
            name={item.price.product?.name}
            // description={item.price.product?.description}
            extra={
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                }}>
                {item.price.type === 'recurring' && item.price.recurring
                  ? [pricing.quantity, t('common.billed', { rule: `${formatRecurring(item.upsell_price?.recurring || item.price.recurring, true, 'per', locale)} ${metered}` })].filter(Boolean).join(', ') // prettier-ignore
                  : pricing.quantity}
              </Box>
            }
          />
          <Stack
            direction="column"
            sx={{
              alignItems: 'flex-end',
              flex: 1,
            }}>
            <Typography sx={{ color: 'text.primary', fontWeight: 500, whiteSpace: 'nowrap' }} gutterBottom>
              {primaryText}
            </Typography>
            {pricing.secondary && (
              <Typography sx={{ fontSize: '0.74375rem', color: 'text.lighter' }}>{pricing.secondary}</Typography>
            )}
          </Stack>
        </Stack>
        {quantityInventoryError ? (
          <Status
            label={quantityInventoryError}
            variant="outlined"
            sx={{
              mt: 1,
              borderColor: 'chip.error.border',
              backgroundColor: 'chip.error.background',
              color: 'chip.error.text',
            }}
          />
        ) : null}

        {/* 数量调整器 */}
        {canAdjustQuantity && !completed && (
          <Box sx={{ mt: 1, p: 1 }}>
            <Stack
              direction="row"
              spacing={1}
              sx={{
                alignItems: 'center',
              }}>
              <Typography
                variant="body2"
                sx={{
                  color: 'text.secondary',
                  minWidth: 'fit-content',
                }}>
                {t('common.quantity')}:
              </Typography>
              <IconButton
                size="small"
                onClick={handleQuantityDecrease}
                disabled={localQuantity <= minQuantity}
                sx={{ minWidth: 32, width: 32, height: 32 }}>
                <Remove fontSize="small" />
              </IconButton>
              <TextField
                size="small"
                value={localQuantity}
                onChange={handleQuantityInputChange}
                sx={{ width: 60 }}
                type="number"
                slotProps={{
                  htmlInput: {
                    min: minQuantity,
                    max: maxQuantity,
                    style: { textAlign: 'center', padding: '4px' },
                  },
                }}
              />
              <IconButton
                size="small"
                onClick={handleQuantityIncrease}
                disabled={localQuantity >= maxQuantity}
                sx={{ minWidth: 32, width: 32, height: 32 }}>
                <Add fontSize="small" />
              </IconButton>
            </Stack>
          </Box>
        )}

        {/* Credit 信息展示 */}
        {isCreditProduct && (
          <Alert severity="info" sx={{ mt: 1, fontSize: '0.875rem' }} icon={false}>
            {formatCreditInfo()}
          </Alert>
        )}

        {children}
      </Stack>
      {canUpsell && !item.upsell_price_id && item.price.upsell?.upsells_to && (
        <Stack
          direction="row"
          className="product-item-upsell"
          sx={{
            alignItems: 'center',
            justifyContent: 'space-between',
            width: '100%',
          }}>
          <Typography
            component="label"
            htmlFor="upsell-switch"
            sx={{
              fontSize: 12,
              cursor: 'pointer',
              color: 'text.secondary',
            }}>
            <Switch
              id="upsell-switch"
              sx={{ mr: 1 }}
              variant="success"
              checked={false}
              onChange={() => onUpsell(item.price_id, item.price.upsell?.upsells_to_id)}
            />
            {t('payment.checkout.upsell.save', {
              recurring: formatRecurring(item.price.upsell.upsells_to.recurring as PriceRecurring, true, 'per', locale),
            })}
            <Status
              label={t('payment.checkout.upsell.off', { saving })}
              variant="outlined"
              sx={{
                ml: 1,
                borderColor: 'chip.warning.border',
                backgroundColor: 'chip.warning.background',
                color: 'chip.warning.text',
              }}
            />
          </Typography>
          <Typography component="span" sx={{ fontSize: 12 }}>
            {formatPrice(item.price.upsell.upsells_to, currency, item.price.product?.unit_label, 1, true, locale)}
          </Typography>
        </Stack>
      )}
      {canUpsell && item.upsell_price_id && (
        <Stack
          direction="row"
          className="product-item-upsell"
          sx={{
            alignItems: 'center',
            justifyContent: 'space-between',
            width: '100%',
          }}>
          <Typography
            component="label"
            htmlFor="upsell-switch"
            sx={{
              fontSize: 12,
              cursor: 'pointer',
              color: 'text.secondary',
            }}>
            <Switch
              id="upsell-switch"
              sx={{ mr: 1 }}
              variant="success"
              checked
              onChange={() => onDownsell(item.upsell_price_id)}
            />
            {t('payment.checkout.upsell.revert', {
              recurring: t(`common.${formatRecurring(item.price.recurring as PriceRecurring)}`),
            })}
          </Typography>
          <Typography component="span" sx={{ fontSize: 12 }}>
            {formatPrice(item.price, currency, item.price.product?.unit_label, 1, true, locale)}
          </Typography>
        </Stack>
      )}
    </Stack>
  );
}
