import { createHash } from 'crypto';

type AnalyticsIdentifyEvent = {
  userId: string;
  traits: {
    email: string;
    name: string;
  };
};

type AnalyticsTrackEvent =
  | {
      name: 'Play Shared Track';
      properties: {
        trackId: string;
        trackName: string;
      };
    }
  | {
      name: 'Seek Shared Track';
      properties: {
        trackId: string;
        trackName: string;
        timeSeconds: number;
        progress: number;
      };
    }
  | {
      name: 'Landing Button Clicked';
      properties: {
        text: string;
        location: string;
      };
    }
  | {
      name: 'Landing Link Clicked';
      properties: {
        text: string;
        location: string;
      };
    }
  | {
      name: 'Experiment Branch Assigned';
      properties: {
        experiment: string;
        branch: string;
      };
    }
  | {
      name: 'Run Quickstart';
      properties: {
        url: string;
        channel?: string;
      };
    }
  | {
      name: 'Started Quickstart Import';
      properties: {
        type: 'url' | 'file';
        url: string | null;
        urlHostname: string | null;
        fileName: string | null;
        fileExtension: string | null;
        fileType: string | null;
        fileSize: number | null;
      };
    }
  | {
      name: 'Finished Quickstart Import';
      properties: {
        type: 'url' | 'file';
        url: string | null;
        urlHostname: string | null;
        fileName: string | null;
        fileExtension: string | null;
        fileType: string | null;
        fileSize: number | null;
        bpm: number | null;
        roundBPM: number | null;
        duration: number;
      };
    }
  | {
      name: 'Opened Quickstart Project';
      properties: {
        type: 'url' | 'file';
        url: string | null;
        urlHostname: string | null;
        fileName: string | null;
        fileExtension: string | null;
        fileType: string | null;
        fileSize: number | null;
        bpm: number | null;
        roundBPM: number | null;
        duration: number;
      };
    }
  | {
      name: 'Clicked Blog Post';
      properties: {
        title: string;
        slug: string;
      };
    };

const correspondingTiktokEvent = {
  'Play Shared Track': {
    name: 'ClickButton',
  },
  'Seek Shared Track': {
    name: 'ClickButton',
  },
  'Landing Button Clicked': {
    name: 'ClickButton',
  },
  'Landing Link Clicked': {
    name: 'ClickButton',
  },
  'Run Quickstart': {
    name: 'ClickButton',
  },
  'Clicked Blog Post': {
    name: 'ClickButton',
  },
};

export const identifyUser = (identifyEvent: AnalyticsIdentifyEvent) => {
  if (process.env.NODE_ENV === 'development') {
    console.log('Would identify:', identifyEvent);
    return;
  }

  const analytics = (window as any).analytics;
  const tiktokPixel = (window as any).ttq;

  if (analytics) {
    analytics.identify(identifyEvent.userId, {
      ...identifyEvent.traits,
    });
  } else {
    console.error('event tracking failed - analytics not set');
  }

  // This is not documented on TikTok Pixel's public documentation, only in the TikTok Ads Manager setup instructions
  // Add this before event code to all pages where PII data postback is expected and appropriate
  // ttq.identify({
  // 	"email": "<hashed_email_address>", // string. The email of the customer if available. It must be hashed with SHA-256 on the client side.
  // 	"phone_number": "<hashed_phone_number>", // string. The phone number of the customer if available. It must be hashed with SHA-256 on the client side.
  // 	"external_id": "<hashed_extenal_id>" // string. Any unique identifier, such as loyalty membership IDs, user IDs, and external cookie IDs.It must be hashed with SHA-256 on the client side.
  // });

  if (tiktokPixel) {
    tiktokPixel.identify({
      email: createHash('sha256').update(`${identifyEvent.traits.email}`).digest('hex'),
      external_id: createHash('sha256').update(`${identifyEvent.userId}`).digest('hex'),
    });
  }
};

const trackAnalyticsEvent = (event: AnalyticsTrackEvent) => {
  setTimeout(() => {
    if (process.env.NODE_ENV === 'development') {
      console.log('Would track:', event);
      return;
    }

    const analytics = (window as any).analytics;
    const tiktokPixel = (window as any).ttq;

    if (analytics) {
      analytics.track(event.name, {
        ...event.properties,
      });
    } else {
      console.error('event tracking failed - analytics not set');
    }

    if (tiktokPixel && event.name in correspondingTiktokEvent) {
      const { name } = correspondingTiktokEvent[event.name as keyof typeof correspondingTiktokEvent];

      const properties = { action: event.name, ...event.properties };

      tiktokPixel.track(name, properties);
    }
  });
};

export default trackAnalyticsEvent;
