import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, formatTime, useMobile, Status, usePaymentContext } from '@blocklet/payment-react';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, AlertTitle, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest, useSetState } from 'ahooks';
import { useNavigate } from 'react-router-dom';
import { dispatch } from 'use-bus';

import Copyable from '../../../../components/copyable';
import EventList from '../../../../components/event/list';
import InfoMetric from '../../../../components/info-metric';
import InfoRow from '../../../../components/info-row';
import InfoRowGroup from '../../../../components/info-row-group';
import MetadataEditor from '../../../../components/metadata/editor';
import MetadataList from '../../../../components/metadata/list';
import SectionHeader from '../../../../components/section/header';
import { goBackOrFallback } from '../../../../libs/util';
import PromotionCodeActions from './actions';
import VerificationConfig from './verification-config';
import PromotionCodeModal from './create';
import CurrencyRestrictions from '../../../../components/promotion/currency-restrictions';
import ActiveRedemptions from '../../../../components/promotion/active-redemptions';

const getPromotionCode = (id: string): Promise<any> => {
  return api.get(`/api/promotion-codes/${id}`).then((res: any) => res.data);
};

const getCoupon = (id: string): Promise<any> => {
  return api.get(`/api/coupons/${id}`).then((res: any) => res.data);
};

export default function PromotionCodeDetail(props: { id: string }) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile();
  const navigate = useNavigate();
  const { settings } = usePaymentContext();
  const [state, setState] = useSetState({
    editing: {
      metadata: false,
    },
    loading: {
      metadata: false,
    },
    editModalOpen: false,
  });

  const { loading, error, data, runAsync } = useRequest(() => getPromotionCode(props.id));
  const { data: couponData } = useRequest(() => (data?.coupon_id ? getCoupon(data.coupon_id) : Promise.resolve(null)), {
    refreshDeps: [data?.coupon_id],
  });

  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

  if (loading || !data) {
    return <CircularProgress />;
  }

  // Get available currencies based on coupon configuration
  const getAvailableCurrencies = () => {
    const allCurrencies = settings.paymentMethods?.flatMap((pm) => pm.payment_currencies) || [];

    if (!couponData) {
      return allCurrencies;
    }

    if (couponData.percent_off) {
      // Percentage coupon: return all available currencies
      return allCurrencies;
    }
    // Fixed amount coupon: return coupon's configured currencies
    const currencyIds = new Set<string>();

    // Add base currency
    if (couponData.currency_id) {
      currencyIds.add(couponData.currency_id);
    }

    // Add additional configured currencies
    if (couponData.currency_options && typeof couponData.currency_options === 'object') {
      Object.keys(couponData.currency_options).forEach((currencyId) => {
        currencyIds.add(currencyId);
      });
    }

    return allCurrencies.filter((currency) => currencyIds.has(currency.id));
  };

  const availableCurrencies = getAvailableCurrencies();

  const onUpdateMetadata = async (updates: any) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, metadata: true } }));
      // 只发送metadata字段，避免其他字段导致验证失败
      await api.put(`/api/promotion-codes/${props.id}`, { metadata: updates.metadata });
      Toast.success(t('common.saved'));
      dispatch('promotion-code.updated');
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, metadata: false } }));
    }
  };

  const handleEditMetadata = () => {
    setState((prev) => ({ editing: { ...prev.editing, metadata: true } }));
  };

  const handleActionsChange = (action: string, promotionCodeData?: any) => {
    if (action === 'edit' && promotionCodeData) {
      setState({ editModalOpen: true });
    } else {
      runAsync();
    }
  };

  const handleEditModalClose = () => {
    setState({ editModalOpen: false });
  };

  const handleEditModalSubmit = () => {
    setState({ editModalOpen: false });
    runAsync();
  };

  const getStatus = () => {
    const isExpired = data.expires_at && Math.floor(Date.now() / 1000) > data.expires_at;
    const isMaxedOut = data.max_redemptions && data.times_redeemed >= data.max_redemptions;
    if (isExpired) {
      return { label: t('admin.promotionCode.expired'), color: 'default' as const };
    }
    if (isMaxedOut) {
      return { label: t('admin.promotionCode.maxedOut'), color: 'default' as const };
    }
    if (!data.active) {
      return { label: t('admin.promotionCode.inactive'), color: 'default' as const };
    }
    return { label: t('admin.promotionCode.active'), color: 'success' as const };
  };

  const formatRedemptions = () => {
    const maxRedemptions = data.max_redemptions ? data.max_redemptions.toString() : t('admin.promotionCode.unlimited');
    const timesRedeemed = data.times_redeemed || 0;
    return `${timesRedeemed}/${maxRedemptions}`;
  };

  const status = getStatus();

  return (
    <Root direction="column" spacing={2.5} sx={{ mb: 4 }}>
      <Box>
        {!data.active && (
          <Alert severity="warning">
            <AlertTitle>{t('admin.promotionCode.inactiveTitle')}</AlertTitle>
            {t('admin.promotionCode.inactiveTip')}
          </Alert>
        )}
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/admin/products/coupons')}
            sx={{
              alignItems: 'center',
              fontWeight: 'normal',
              cursor: 'pointer',
            }}>
            <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
            <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
              {t('admin.coupons')}
            </Typography>
          </Stack>
          <Stack direction="row" spacing={2}>
            <PromotionCodeActions data={data} onChange={handleActionsChange} variant="normal" />
          </Stack>
        </Stack>
        <Box
          sx={{
            mt: 4,
            mb: 3,
            display: 'flex',
            gap: {
              xs: 2,
              sm: 2,
              md: 5,
            },
            flexWrap: 'wrap',
            flexDirection: {
              xs: 'column',
              sm: 'column',
              md: 'row',
            },
            alignItems: {
              xs: 'flex-start',
              sm: 'flex-start',
              md: 'center',
            },
          }}>
          <Stack
            direction="column"
            sx={{
              alignItems: 'flex-start',
              justifyContent: 'space-around',
            }}>
            <Typography
              variant="h2"
              sx={{
                color: 'text.primary',
                fontFamily: 'monospace',
                letterSpacing: 1,
              }}>
              {data.code}
            </Typography>
          </Stack>
          <Stack
            className="section-body"
            sx={{
              justifyContent: 'flex-start',
              flexWrap: 'wrap',
              'hr.MuiDivider-root:last-child': {
                display: 'none',
              },
              flexDirection: {
                xs: 'column',
                sm: 'column',
                md: 'row',
              },
              alignItems: 'flex-start',
              gap: {
                xs: 1,
                sm: 1,
                md: 3,
              },
            }}>
            <InfoMetric
              label={t('admin.promotionCode.id')}
              value={<Copyable text={props.id} style={{ marginLeft: 4 }} />}
              divider
            />
            <InfoMetric label={t('admin.promotionCode.redemptions')} value={formatRedemptions()} divider />
            <InfoMetric
              label={t('admin.promotionCode.status')}
              value={<Status label={status.label} color={status.color} />}
              divider
            />
            <InfoMetric
              label={t('admin.promotionCode.verificationType')}
              value={t(`admin.promotionCode.verificationTypeMap.${data.verification_type}`)}
              divider
            />
            <InfoMetric label={t('admin.promotionCode.created')} value={formatTime(data.created_at)} divider />
          </Stack>
        </Box>
        <Divider />
      </Box>
      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.promotion-code-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.promotion-code-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box
          className="promotion-code-column-1"
          sx={{
            flex: 1,
            gap: 2.5,
            display: 'flex',
            flexDirection: 'column',
          }}>
          <Box className="section">
            <SectionHeader title={t('common.details')} />
            <InfoRowGroup>
              <InfoRow
                label={t('common.active')}
                value={data.active ? t('admin.promotionCode.yes') : t('admin.promotionCode.no')}
              />
              {data.description && <InfoRow label={t('admin.coupon.desc')} value={data.description} />}
              <InfoRow
                label={t('admin.promotionCode.couponId')}
                value={
                  <Button
                    variant="text"
                    color="inherit"
                    size="small"
                    sx={{
                      color: 'secondary.main',
                    }}
                    onClick={() => navigate(`/admin/products/coupons/${data.coupon_id}`)}>
                    {data.coupon_id}
                  </Button>
                }
              />
              <InfoRow
                label={t('admin.promotionCode.maxRedemptions')}
                value={data.max_redemptions || t('admin.promotionCode.unlimited')}
              />
              <InfoRow label={t('admin.promotionCode.timesRedeemed')} value={data.times_redeemed || 0} />
              <InfoRow
                label={t('admin.promotionCode.expires')}
                value={data.expires_at ? formatTime(data.expires_at * 1000) : t('admin.promotionCode.never')}
              />
              <InfoRow label={t('admin.promotionCode.updated')} value={formatTime(data.updated_at)} />
            </InfoRowGroup>
          </Box>

          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.promotionCode.verificationConfig')} />
            <Box className="section-body">
              <VerificationConfig data={data} />
            </Box>
          </Box>

          {data.restrictions?.currency_options && Object.keys(data.restrictions.currency_options).length > 0 && (
            <>
              <Divider />
              <Box className="section">
                <SectionHeader title={t('admin.coupon.currencies')} />
                <Box className="section-body">
                  <CurrencyRestrictions currencyOptions={data.restrictions.currency_options} type="promotion_code" />
                </Box>
              </Box>
            </>
          )}

          <Divider />
          <Box className="section">
            <SectionHeader title={t('admin.coupon.activeRedemptions')} />
            <Box className="section-body">
              <ActiveRedemptions promotionCodeId={data.id} />
            </Box>
          </Box>

          <Divider />
          <Box className="section">
            <SectionHeader title={t('common.events')} />
            <Box className="section-body">
              <EventList features={{ toolbar: false }} object_id={data.id} />
            </Box>
          </Box>
        </Box>
        {isMobile && <Divider />}
        <Box className="promotion-code-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          <Box className="section">
            <SectionHeader title={t('common.metadata.label')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                disabled={state.editing.metadata}
                onClick={handleEditMetadata}>
                {t('common.edit')}
              </Button>
            </SectionHeader>
            <Box className="section-body">
              <MetadataList data={data.metadata} handleEditMetadata={handleEditMetadata} />
              {state.editing.metadata && (
                <MetadataEditor
                  data={data}
                  loading={state.loading.metadata}
                  onSave={onUpdateMetadata}
                  onCancel={() => setState((prev) => ({ editing: { ...prev.editing, metadata: false } }))}
                />
              )}
            </Box>
          </Box>
        </Box>
      </Stack>

      <PromotionCodeModal
        open={state.editModalOpen}
        onClose={handleEditModalClose}
        onSubmit={handleEditModalSubmit}
        couponId={data.coupon_id}
        promotionCode={data}
        isEditing
        availableCurrencies={availableCurrencies}
      />
    </Root>
  );
}

const Root = styled(Stack)``;
