import { TemplateBase } from "../base-template";
import {
  BaseTemplate,
  BaseComponent,
  ComponentType,
  ServiceTier,
  TemplateContext,
} from "../../../types/template-system";

/**
 * Plus 티어 템플릿 클래스
 * 모든 기능이 포함된 프리미엄 티어 템플릿
 */
export class PlusTemplate extends TemplateBase {
  constructor(template: BaseTemplate) {
    super(template);
    this.template.tier = ServiceTier.PLUS;
    this.initializePlusFeatures();
  }

  /**
   * Plus tier 허용 컴포넌트 타입
   */
  private static readonly ALLOWED_COMPONENTS: ComponentType[] = [
    ComponentType.HEADER,
    ComponentType.HERO,
    ComponentType.ABOUT,
    ComponentType.SERVICES,
    ComponentType.TESTIMONIALS,
    ComponentType.TEAM,
    ComponentType.CONTACT,
    ComponentType.FOOTER,
    ComponentType.BLOG, // Plus tier exclusive
    ComponentType.NEWSLETTER, // Plus tier exclusive
    ComponentType.SOCIAL, // Plus tier exclusive
  ];

  /**
   * Plus tier 전용 고급 기능
   */
  private static readonly PLUS_FEATURES = [
    "white-label",
    "multi-language",
    "e-commerce-integration",
    "advanced-analytics",
    "custom-domains",
    "api-integration",
    "automation",
    "priority-support",
  ];

  /**
   * 컴포넌트 props 생성
   */
  protected createComponentProps(
    component: BaseComponent,
    context: TemplateContext
  ): Record<string, unknown> {
    // Plus tier 기본 props
    const baseProps = {
      id: component.id,
      type: component.type,
      title: component.title,
      description: component.description,
      settings: component.settings,
      context: context,
    };

    // Plus tier 고급 기능 추가
    return {
      ...baseProps,
      isPlusFeature: true,
      customizationLevel: "advanced",
      theme: this.template.globalSettings.theme || {},
      tier: ServiceTier.PLUS,
      advancedSettings: this.template.globalSettings.customProperties || {},
    };
  }

  /**
   * 컴포넌트 추가 시 Plus tier 제한 검증
   */
  public override addComponent(component: BaseComponent): boolean {
    // Plus tier는 모든 컴포넌트 허용
    if (!PlusTemplate.ALLOWED_COMPONENTS.includes(component.type)) {
      throw new Error(
        `Plus tier에서 지원하지 않는 컴포넌트입니다: ${component.type}`
      );
    }

    // 최대 컴포넌트 수 제한 없음 (Plus tier)
    this.template.components.push(component);
    return true;
  }

  /**
   * Plus tier 고급 기능 활성화
   */
  private enableAdvancedFeature(featureName: string): void {
    if (!this.template.globalSettings.customProperties) {
      this.template.globalSettings.customProperties = {};
    }

    if (!this.template.globalSettings.customProperties.features) {
      this.template.globalSettings.customProperties.features = [];
    }

    const features = this.template.globalSettings.customProperties
      .features as string[];
    if (!features.includes(featureName)) {
      features.push(featureName);
    }
  }

  /**
   * 화이트 라벨링 설정
   */
  public configureWhiteLabel(config: {
    hidePoweredBy: boolean;
    customBranding?: {
      logo?: string;
      companyName?: string;
      primaryColor?: string;
    };
  }): void {
    this.enableAdvancedFeature("white-label");

    if (!this.template.globalSettings.customProperties) {
      this.template.globalSettings.customProperties = {};
    }
    this.template.globalSettings.customProperties.whiteLabel = config;
  }

  /**
   * 다국어 지원 설정
   */
  public configureMultiLanguage(
    languages: string[],
    defaultLanguage: string
  ): void {
    this.enableAdvancedFeature("multi-language");

    if (!this.template.globalSettings.customProperties) {
      this.template.globalSettings.customProperties = {};
    }
    this.template.globalSettings.customProperties.i18n = {
      supportedLanguages: languages,
      defaultLanguage,
      enabled: true,
    };
  }

  /**
   * 전자상거래 통합 설정
   */
  public configureECommerce(config: {
    provider: "shopify" | "woocommerce" | "stripe";
    apiKey: string;
    enablePayments: boolean;
    currency: string;
  }): void {
    this.enableAdvancedFeature("e-commerce-integration");

    if (!this.template.globalSettings.customProperties) {
      this.template.globalSettings.customProperties = {};
    }
    this.template.globalSettings.customProperties.ecommerce = config;
  }

  /**
   * 고급 분석 설정
   */
  public configureAdvancedAnalytics(config: {
    googleAnalyticsId?: string;
    facebookPixelId?: string;
    customTracking?: boolean;
    heatmaps?: boolean;
    userRecording?: boolean;
  }): void {
    this.enableAdvancedFeature("advanced-analytics");

    if (!this.template.globalSettings.customProperties) {
      this.template.globalSettings.customProperties = {};
    }
    const existingAnalytics =
      this.template.globalSettings.customProperties.analytics || {};
    this.template.globalSettings.customProperties.analytics = {
      ...existingAnalytics,
      ...config,
    };
  }

  /**
   * Plus tier 검증
   */
  public override validate(): { isValid: boolean; errors: string[] } {
    const baseValidation = super.validate();
    const errors = [...baseValidation.errors];

    // Plus tier specific validations
    const componentCount = this.template.components.length;

    // Plus tier는 컴포넌트 수 제한 없음, 하지만 권장 사항 확인
    if (componentCount > 15) {
      errors.push(
        "Plus tier에서도 성능을 위해 15개 이하의 컴포넌트를 권장합니다."
      );
    }

    // Plus tier 전용 컴포넌트 확인
    const hasTeam = this.template.components.some(
      (c) => c.type === ComponentType.TEAM
    );

    if (!hasTeam) {
      errors.push(
        "Plus tier에서는 고급 기능 활용을 위해 Team 컴포넌트 사용을 권장합니다."
      );
    }

    // 고급 기능 사용 권장
    const features =
      (this.template.globalSettings.customProperties?.features as string[]) ||
      [];
    const advancedFeaturesUsed = features.filter((f) =>
      PlusTemplate.PLUS_FEATURES.includes(f)
    ).length;

    if (advancedFeaturesUsed === 0) {
      errors.push(
        "Plus tier의 고급 기능을 활용해보세요. (화이트라벨, 다국어 지원 등)"
      );
    }

    return {
      isValid: errors.length === 0,
      errors,
    };
  }

  /**
   * 다운그레이드 시 경고사항 반환
   */
  public getDowngradeWarnings(targetTier: ServiceTier): {
    removedComponents: ComponentType[];
    disabledFeatures: string[];
    dataLoss: string[];
  } {
    const removedComponents: ComponentType[] = [];
    const disabledFeatures: string[] = [];
    const dataLoss: string[] = [];

    if (targetTier === ServiceTier.STARTER) {
      // Starter tier로 다운그레이드
      const starterAllowed = [
        ComponentType.HEADER,
        ComponentType.HERO,
        ComponentType.CONTACT,
        ComponentType.FOOTER,
      ];

      removedComponents.push(
        ...this.template.components
          .map((c) => c.type)
          .filter((type) => !starterAllowed.includes(type))
      );

      disabledFeatures.push(...PlusTemplate.PLUS_FEATURES);
      dataLoss.push("모든 고급 설정", "커스텀 브랜딩", "다국어 콘텐츠");
    } else if (targetTier === ServiceTier.STANDARD) {
      // Standard tier로 다운그레이드
      const standardAllowed = [
        ComponentType.HEADER,
        ComponentType.HERO,
        ComponentType.ABOUT,
        ComponentType.SERVICES,
        ComponentType.TESTIMONIALS,
        ComponentType.CONTACT,
        ComponentType.FOOTER,
      ];

      removedComponents.push(
        ...this.template.components
          .map((c) => c.type)
          .filter((type) => !standardAllowed.includes(type))
      );

      // Plus tier 전용 기능 사용 시 경고
      const features =
        (this.template.globalSettings.customProperties?.features as string[]) ||
        [];
      const plusFeatures = features.filter((f) =>
        PlusTemplate.PLUS_FEATURES.includes(f)
      );

      disabledFeatures.push(...plusFeatures);
      dataLoss.push("화이트라벨 설정", "고급 분석", "전자상거래 통합");
    }

    return {
      removedComponents,
      disabledFeatures,
      dataLoss,
    };
  }

  /**
   * Plus tier 성능 분석
   */
  public getPerformanceAnalysis(): {
    score: number;
    recommendations: string[];
    advancedFeatures: number;
    integrations: number;
  } {
    const features =
      (this.template.globalSettings.customProperties?.features as string[]) ||
      [];
    const advancedFeatures = features.filter((f) =>
      PlusTemplate.PLUS_FEATURES.includes(f)
    ).length;

    const customProps = this.template.globalSettings.customProperties || {};
    const integrations = [
      customProps.analytics,
      customProps.ecommerce,
      customProps.i18n,
    ].filter(Boolean).length;

    // 성능 점수 계산 (컴포넌트 수와 기능 수 기반)
    const componentCount = this.template.components.length;
    const baseScore = Math.max(0, 100 - componentCount * 2);
    const featureBonus = Math.min(20, advancedFeatures * 5);
    const integrationBonus = Math.min(15, integrations * 5);

    const score = Math.min(100, baseScore + featureBonus + integrationBonus);

    const recommendations: string[] = [];

    if (componentCount > 12) {
      recommendations.push("컴포넌트 수를 줄여 로딩 속도를 개선하세요");
    }

    if (advancedFeatures < 2) {
      recommendations.push("Plus tier 고급 기능을 더 활용해보세요");
    }

    if (integrations === 0) {
      recommendations.push("외부 서비스 통합을 고려해보세요");
    }

    return {
      score,
      recommendations,
      advancedFeatures,
      integrations,
    };
  }

  /**
   * Plus tier 초기화
   */
  private initializePlusFeatures(): void {
    if (!this.template.globalSettings.customProperties) {
      this.template.globalSettings.customProperties = {};
    }

    // Plus tier 기본 설정
    this.template.globalSettings.customProperties.tier = ServiceTier.PLUS;
    this.template.globalSettings.customProperties.maxComponents = -1; // 무제한
    this.template.globalSettings.customProperties.advancedCustomization = true;
    this.template.globalSettings.customProperties.prioritySupport = true;
  }
}
