import { getUrl } from '@blocklet/sdk/lib/component';
import { withQuery } from 'ufo';
import { getConnectQueryParam, getOwnerDid } from '../../util';
import { translate } from '../../../locales';
import type { BaseEmailTemplate, BaseEmailTemplateType } from './base';
import { getUserLocale } from '../../../integrations/blocklet/notification';

/**
 * Exchange Rate Alert Types
 */
export type ExchangeRateAlertType = 'spread_exceeded' | 'providers_unavailable';

export interface ExchangeRateAlertEmailTemplateOptions {
  alertType: ExchangeRateAlertType;
  symbol: string;
  severity: string;
  timestamp: string;
  // For spread_exceeded
  spreadPercent?: string;
  threshold?: number;
  // Provider info
  providers: Array<{
    id: string;
    name: string;
    rate?: string;
  }>;
}

interface ExchangeRateAlertEmailTemplateContext {
  locale: string;
  userDid: string;
  alertType: ExchangeRateAlertType;
  symbol: string;
  severity: string;
  timestamp: string;
  spreadPercent?: string;
  threshold?: number;
  providers: Array<{
    id: string;
    name: string;
    rate?: string;
  }>;
  viewProvidersLink: string;
}

export class ExchangeRateAlertEmailTemplate implements BaseEmailTemplate<ExchangeRateAlertEmailTemplateContext> {
  options: ExchangeRateAlertEmailTemplateOptions;

  constructor(options: ExchangeRateAlertEmailTemplateOptions) {
    this.options = options;
  }

  async getContext(): Promise<ExchangeRateAlertEmailTemplateContext> {
    const userDid = await getOwnerDid();
    if (!userDid) {
      throw new Error('get owner did failed');
    }

    const locale = await getUserLocale(userDid);

    const viewProvidersLink = getUrl(
      withQuery('admin/products/exchange-rate-providers', {
        locale,
        ...getConnectQueryParam({ userDid }),
      })
    );

    return {
      userDid,
      locale,
      alertType: this.options.alertType,
      symbol: this.options.symbol,
      severity: this.options.severity,
      timestamp: this.options.timestamp,
      spreadPercent: this.options.spreadPercent,
      threshold: this.options.threshold,
      providers: this.options.providers,
      viewProvidersLink,
    };
  }

  async getTemplate(): Promise<BaseEmailTemplateType> {
    const { locale, alertType, symbol, spreadPercent, threshold, providers, timestamp, viewProvidersLink } =
      await this.getContext();

    const titleKey = `notification.exchangeRateAlert.${alertType}.title`;
    const bodyKey = `notification.exchangeRateAlert.${alertType}.body`;

    const titleParams: Record<string, any> = { symbol };
    const bodyParams: Record<string, any> = { symbol };

    if (alertType === 'spread_exceeded') {
      titleParams.spreadPercent = spreadPercent;
      bodyParams.spreadPercent = spreadPercent;
      bodyParams.threshold = threshold;
    }

    // Build provider list for attachments
    const providerFields: any[] = [];

    // Add timestamp
    providerFields.push(
      {
        type: 'text',
        data: {
          type: 'plain',
          color: '#9397A1',
          text: translate('notification.exchangeRateAlert.timestamp', locale),
        },
      },
      {
        type: 'text',
        data: {
          type: 'plain',
          text: timestamp,
        },
      }
    );

    // Add symbol
    providerFields.push(
      {
        type: 'text',
        data: {
          type: 'plain',
          color: '#9397A1',
          text: translate('notification.exchangeRateAlert.symbol', locale),
        },
      },
      {
        type: 'text',
        data: {
          type: 'plain',
          text: symbol,
        },
      }
    );

    // Add spread info for spread_exceeded
    if (alertType === 'spread_exceeded' && spreadPercent) {
      providerFields.push(
        {
          type: 'text',
          data: {
            type: 'plain',
            color: '#9397A1',
            text: translate('notification.exchangeRateAlert.spread', locale),
          },
        },
        {
          type: 'text',
          data: {
            type: 'plain',
            color: '#FF6600',
            text: `${spreadPercent}% (threshold: ${threshold}%)`,
          },
        }
      );
    }

    // Add provider rates
    if (providers.length > 0) {
      providerFields.push(
        {
          type: 'text',
          data: {
            type: 'plain',
            color: '#9397A1',
            text: translate('notification.exchangeRateAlert.providers', locale),
          },
        },
        {
          type: 'text',
          data: {
            type: 'plain',
            text: providers.map((p) => `${p.name}: ${p.rate || 'N/A'}`).join('\n'),
          },
        }
      );
    }

    const template: BaseEmailTemplateType = {
      title: translate(titleKey, locale, titleParams),
      body: translate(bodyKey, locale, bodyParams),
      attachments: [
        {
          type: 'section',
          fields: providerFields,
        },
      ],
      actions: [
        {
          name: translate('notification.exchangeRateAlert.viewProviders', locale),
          title: translate('notification.exchangeRateAlert.viewProviders', locale),
          link: viewProvidersLink,
        },
      ],
    };

    return template;
  }
}
