import mixpanel, { type MixpanelInstance } from "mixpanel-browser";

type MixpanelEvent =
  | "user_signedup"
  | "user_signedin"
  | "user_signedout"
  | "project_created"
  | "project_updated"
  | "project_deleted"
  | "screenplay_created"
  | "screenplay_updated"
  | "screenplay exported"
  | "subscription_started"
  | "subscription_renewed"
  | "subscription_cancelled"
  | "payment_succeeded"
  | "payment_failed"
  | "invitation_sent"
  | "collaboration_started"
  | "collaboration_updated"
  | "export_completed"
  | "import_completed";

export interface MixpanelConfig {
  projectToken: string;
  options?: {
    debug?: boolean;
    track_pageview?: boolean;
    persistence?: "localStorage" | "cookie" | "memory";
    loaded?: (mixpanel: MixpanelInstance) => void;
  };
}

export class MixpanelService {
  private mixpanel: MixpanelInstance;
  private initialized: boolean = false;

  constructor(config: MixpanelConfig) {
    this.mixpanel = mixpanel.init(config.projectToken, config.options);
    this.initialized = true;
  }

  track(event: MixpanelEvent, properties?: Record<string, unknown>): void {
    if (!this.initialized) {
      console.warn("Mixpanel not initialized");
      return;
    }
    this.mixpanel.track(event, properties);
  }

  identify(userId: string, properties?: Record<string, unknown>): void {
    this.mixpanel.identify(userId);
    if (properties) {
      this.mixpanel.people.set(userId, properties);
    }
  }

  alias(distinctId: string, alias: string): void {
    this.mixpanel.alias(alias, distinctId);
  }

  reset(): void {
    this.mixpanel.reset();
  }

  getDistinctId(): string {
    return this.mixpanel.get_distinct_id();
  }

  group(groupType: string, groupId: string): void {
    this.mixpanel.group(groupType, groupId);
  }

  trackWithTimestamp(event: MixpanelEvent, timestamp: Date, properties?: Record<string, unknown>): void {
    this.mixpanel.track(event, {
      ...properties,
      timestamp: timestamp.toISOString(),
    });
  }
}

export const createMixpanelService = (config: MixpanelConfig): MixpanelService => {
  return new MixpanelService(config);
};
