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

/**
 * Standard Tier Template Implementation
 * Starter 기능 + 추가 비즈니스 컴포넌트들을 포함한 스탠다드 티어 템플릿
 */
export class StandardTemplate extends TemplateBase {
  constructor(template: BaseTemplate) {
    super(template);

    // Standard tier validation
    if (template.tier !== ServiceTier.STANDARD) {
      throw new Error(
        "StandardTemplate can only be used with STANDARD tier templates"
      );
    }
  }

  /**
   * Standard tier에서 허용되는 컴포넌트 타입들
   */
  private static readonly ALLOWED_COMPONENTS: ComponentType[] = [
    ComponentType.HERO,
    ComponentType.ABOUT,
    ComponentType.SERVICES,
    ComponentType.TESTIMONIALS,
    ComponentType.PORTFOLIO,
    ComponentType.CONTACT,
    ComponentType.FOOTER,
  ];

  protected createComponentProps(
    component: BaseComponent,
    context: TemplateContext
  ): Record<string, unknown> {
    const baseProps = super.createComponentProps(component, context);

    // Standard tier specific prop enhancements
    switch (component.type) {
      case ComponentType.SERVICES:
        return {
          ...baseProps,
          layout: component.settings?.layout || "grid-3",
          showFeatures: component.settings?.showFeatures ?? true,
          showIcons: component.settings?.showIcons ?? true,
          services: component.content?.services || [],
        };

      case ComponentType.TESTIMONIALS:
        return {
          ...baseProps,
          layout: component.settings?.layout || "grid",
          showRatings: component.settings?.showRatings ?? true,
          showAvatars: component.settings?.showAvatars ?? true,
          showCompany: component.settings?.showCompany ?? true,
          testimonials: component.content?.testimonials || [],
        };

      case ComponentType.PORTFOLIO:
        return {
          ...baseProps,
          layout: component.settings?.layout || "grid",
          showFilters: component.settings?.showFilters ?? true,
          showTechnologies: component.settings?.showTechnologies ?? true,
          portfolioItems: component.content?.portfolioItems || [],
          categories: component.content?.categories || [],
        };

      default:
        return baseProps;
    }
  }

  public override addComponent(component: BaseComponent): boolean {
    // Check if component type is allowed for Standard tier
    if (!StandardTemplate.ALLOWED_COMPONENTS.includes(component.type)) {
      throw new Error(
        `Component type '${component.type}' is not available in Standard tier. ` +
          `Available components: ${StandardTemplate.ALLOWED_COMPONENTS.join(
            ", "
          )}`
      );
    }

    // Standard tier specific validation
    const maxComponents = this.getMaxComponents();
    if (this.template.components.length >= maxComponents) {
      throw new Error(
        `Standard tier is limited to ${maxComponents} components. ` +
          `Upgrade to Plus tier for unlimited components.`
      );
    }

    return super.addComponent(component);
  }

  public override validate(): { isValid: boolean; errors: string[] } {
    const baseValidation = super.validate();
    const errors = [...baseValidation.errors];

    // Standard tier specific validations
    const componentTypes = this.template.components.map((c) => c.type);

    // Check for component limits
    const maxComponents = this.getMaxComponents();
    if (this.template.components.length > maxComponents) {
      errors.push(
        `Too many components (${this.template.components.length}). Standard tier allows maximum ${maxComponents} components.`
      );
    }

    // Check for disallowed components
    const disallowedComponents = componentTypes.filter(
      (type) => !StandardTemplate.ALLOWED_COMPONENTS.includes(type)
    );
    if (disallowedComponents.length > 0) {
      errors.push(
        `Disallowed components for Standard tier: ${disallowedComponents.join(
          ", "
        )}`
      );
    }

    // Standard tier should have HERO and at least one business component
    if (!componentTypes.includes(ComponentType.HERO)) {
      errors.push("Standard tier templates must include a HERO component");
    }

    const businessComponents = [
      ComponentType.SERVICES,
      ComponentType.TESTIMONIALS,
      ComponentType.PORTFOLIO,
    ];
    const hasBusinessComponent = businessComponents.some((type) =>
      componentTypes.includes(type)
    );
    if (!hasBusinessComponent) {
      errors.push(
        "Standard tier templates should include at least one business component (SERVICES, TESTIMONIALS, or PORTFOLIO)"
      );
    }

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

  private getMaxComponents(): number {
    return 7; // Standard tier allows up to 7 components
  }

  /**
   * Standard tier에서 Plus tier로의 업그레이드 경로
   */
  public getUpgradePath(): {
    nextTier: ServiceTier;
    newFeatures: string[];
    additionalComponents: ComponentType[];
  } {
    return {
      nextTier: ServiceTier.PLUS,
      newFeatures: [
        "Unlimited components",
        "Advanced animations",
        "Custom CSS/JS",
        "E-commerce integration",
        "Team collaboration",
        "Advanced analytics",
        "Multi-language support",
        "API access",
      ],
      additionalComponents: [
        ComponentType.TEAM,
        ComponentType.PRICING,
        ComponentType.BLOG,
        ComponentType.FAQ,
      ],
    };
  }

  /**
   * Standard tier의 제한사항
   */
  public getLimitations(): {
    maxComponents: number;
    allowedComponents: ComponentType[];
    customizationLimits: string[];
  } {
    return {
      maxComponents: this.getMaxComponents(),
      allowedComponents: StandardTemplate.ALLOWED_COMPONENTS,
      customizationLimits: [
        "Basic theme customization only",
        "Limited color schemes",
        "Standard fonts only",
        "No custom CSS/JS",
        "Basic image optimization",
        "Standard SEO features",
      ],
    };
  }

  /**
   * Standard tier 특화 설정 업데이트
   */
  public updateStandardSettings(settings: {
    primaryColor?: string;
    secondaryColor?: string;
    accentColor?: string;
    fontFamily?: string;
    companyName?: string;
    businessType?: string;
    showBranding?: boolean;
  }): void {
    const currentSettings = this.template.globalSettings;

    this.template.globalSettings = {
      ...currentSettings,
      colors: {
        ...currentSettings.colors,
        primary: settings.primaryColor || currentSettings.colors?.primary,
        secondary: settings.secondaryColor || currentSettings.colors?.secondary,
        accent: settings.accentColor || currentSettings.colors?.accent,
      },
      typography: {
        ...currentSettings.typography,
        fontFamily:
          settings.fontFamily || currentSettings.typography?.fontFamily,
      },
      branding: {
        ...currentSettings.branding,
        companyName:
          settings.companyName || currentSettings.branding?.companyName,
        businessType:
          settings.businessType || currentSettings.branding?.businessType,
        showBranding:
          settings.showBranding ?? currentSettings.branding?.showBranding,
      },
    };
  }

  /**
   * Standard tier의 고급 기능들
   */
  public getStandardFeatures(): {
    analytics: boolean;
    formIntegration: boolean;
    socialMediaIntegration: boolean;
    basicSEO: boolean;
    responsiveDesign: boolean;
    contentManagement: boolean;
  } {
    return {
      analytics: true,
      formIntegration: true,
      socialMediaIntegration: true,
      basicSEO: true,
      responsiveDesign: true,
      contentManagement: true,
    };
  }
}
