/**
 * Analytics Events Tracker
 *
 * Comprehensive event tracking for key user actions across the platform.
 * Integrates with PostHog, Google Analytics, and custom analytics backend.
 *
 * Event Categories:
 * - CTA Events: Demo bookings, contact forms, pricing interactions
 * - Feature Usage: Dashboard, billing, appointments, settings
 * - User Journey: Onboarding, authentication, navigation
 * - Error Events: Form errors, API failures, validation issues
 * - Engagement: Video plays, resource downloads, case study views
 */

// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { prisma } from "../db";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { createId } from "@paralleldrive/cuid2";
import { logger } from "@/lib/logger";

// Extend Window interface for analytics libraries
declare global {
  interface Window {
    posthog?: {
      capture: (event: string, properties?: Record<string, unknown>) => void;
    };
    gtag?: (...args: unknown[]) => void;
  }
}

// ==================== EVENT TYPES ====================

export enum EventCategory {
  CTA = "cta",
  FEATURE_USAGE = "feature_usage",
  USER_JOURNEY = "user_journey",
  ERROR = "error",
  ENGAGEMENT = "engagement",
  CONVERSION = "conversion",
  NAVIGATION = "navigation",
}

export enum EventName {
  // CTA Events (7 events)
  CTA_DEMO_BOOKING_STARTED = "cta_demo_booking_started",
  CTA_DEMO_BOOKING_COMPLETED = "cta_demo_booking_completed",
  CTA_CONTACT_FORM_OPENED = "cta_contact_form_opened",
  CTA_CONTACT_FORM_SUBMITTED = "cta_contact_form_submitted",
  CTA_PRICING_VIEWED = "cta_pricing_viewed",
  CTA_PRICING_PLAN_SELECTED = "cta_pricing_plan_selected",
  CTA_FREE_TRIAL_CLICKED = "cta_free_trial_clicked",

  // Feature Usage Events (8 events)
  FEATURE_DASHBOARD_VIEWED = "feature_dashboard_viewed",
  FEATURE_APPOINTMENT_CREATED = "feature_appointment_created",
  FEATURE_APPOINTMENT_CANCELLED = "feature_appointment_cancelled",
  FEATURE_BILLING_VIEWED = "feature_billing_viewed",
  FEATURE_SUBSCRIPTION_UPGRADED = "feature_subscription_upgraded",
  FEATURE_SUBSCRIPTION_CANCELLED = "feature_subscription_cancelled",
  FEATURE_SETTINGS_UPDATED = "feature_settings_updated",
  FEATURE_TEAM_MEMBER_INVITED = "feature_team_member_invited",

  // User Journey Events (6 events)
  USER_SIGNUP_STARTED = "user_signup_started",
  USER_SIGNUP_COMPLETED = "user_signup_completed",
  USER_LOGIN_SUCCESS = "user_login_success",
  USER_LOGIN_FAILED = "user_login_failed",
  USER_LOGOUT = "user_logout",
  USER_ONBOARDING_COMPLETED = "user_onboarding_completed",

  // Error Events (5 events)
  ERROR_FORM_VALIDATION = "error_form_validation",
  ERROR_API_REQUEST = "error_api_request",
  ERROR_PAYMENT_FAILED = "error_payment_failed",
  ERROR_PAGE_NOT_FOUND = "error_page_not_found",
  ERROR_SESSION_EXPIRED = "error_session_expired",

  // Engagement Events (5 events)
  ENGAGEMENT_VIDEO_PLAYED = "engagement_video_played",
  ENGAGEMENT_RESOURCE_DOWNLOADED = "engagement_resource_downloaded",
  ENGAGEMENT_CASE_STUDY_VIEWED = "engagement_case_study_viewed",
  ENGAGEMENT_FAQ_EXPANDED = "engagement_faq_expanded",
  ENGAGEMENT_CHATBOT_OPENED = "engagement_chatbot_opened",

  // Conversion Events (3 events)
  CONVERSION_LEAD_CAPTURED = "conversion_lead_captured",
  CONVERSION_TRIAL_STARTED = "conversion_trial_started",
  CONVERSION_PAID_CUSTOMER = "conversion_paid_customer",

  // Navigation Events (2 events)
  NAVIGATION_PAGE_VIEW = "navigation_page_view",
  NAVIGATION_EXTERNAL_LINK_CLICKED = "navigation_external_link_clicked",
}

export interface EventProperties {
  // Common properties
  userId?: string;
  sessionId?: string;
  page?: string;
  language?: "en" | "ar";

  // CTA specific
  ctaType?: string;
  ctaLocation?: string;
  formName?: string;
  planName?: string;
  planPrice?: number;

  // Feature specific
  featureName?: string;
  actionType?: string;
  resourceType?: string;

  // Error specific
  errorMessage?: string;
  errorCode?: string;
  stackTrace?: string;

  // Engagement specific
  videoId?: string;
  videoDuration?: number;
  resourceId?: string;
  caseStudyId?: string;

  // Conversion specific
  source?: string;
  medium?: string;
  campaign?: string;
  value?: number;

  // Navigation specific
  referrer?: string;
  destination?: string;

  // Custom properties
  [key: string]: string | number | boolean | undefined | null;
}

// ==================== TRACKING FUNCTIONS ====================

/**
 * Track a custom event
 *
 * DISABLED: Database tracking disabled - Missing Prisma model (analytics_events)
 * Still sends to PostHog and Google Analytics for client-side tracking
 */
export async function trackEvent(
  eventName: EventName,
  category: EventCategory,
  properties: EventProperties = {},
): Promise<void> {
  try {
    /* DISABLED - Missing Prisma model analytics_events
    // Store in database for analytics
    await prisma.analytics_events.create({
      data: {
        id: createId(),
        eventName,
        category,
        properties: properties as Record<string, unknown>,
        userId: properties.userId || null,
        sessionId: properties.sessionId || null,
        page: properties.page || null,
        createdAt: new Date(),
      },
    });
    */

    // Also send to PostHog if available (client-side integration)
    if (typeof window !== "undefined" && window.posthog) {
      window.posthog.capture(eventName, {
        category,
        ...properties,
      });
    }

    // Send to Google Analytics if available
    if (typeof window !== "undefined" && window.gtag) {
      window.gtag("event", eventName, {
        event_category: category,
        ...properties,
      });
    }
  } catch (error) {
    // Silent fail - don't break user experience
    logger.error("Failed to track event", error, {
      eventName,
      category,
      service: "analytics",
    });
  }
}

// ==================== CTA TRACKING ====================

export async function trackDemoBookingStarted(
  properties: EventProperties = {},
) {
  return trackEvent(EventName.CTA_DEMO_BOOKING_STARTED, EventCategory.CTA, {
    ctaType: "demo_booking",
    ...properties,
  });
}

export async function trackDemoBookingCompleted(
  properties: EventProperties = {},
) {
  return trackEvent(EventName.CTA_DEMO_BOOKING_COMPLETED, EventCategory.CTA, {
    ctaType: "demo_booking",
    ...properties,
  });
}

export async function trackContactFormOpened(properties: EventProperties = {}) {
  return trackEvent(EventName.CTA_CONTACT_FORM_OPENED, EventCategory.CTA, {
    ctaType: "contact_form",
    ...properties,
  });
}

export async function trackContactFormSubmitted(
  properties: EventProperties = {},
) {
  return trackEvent(EventName.CTA_CONTACT_FORM_SUBMITTED, EventCategory.CTA, {
    ctaType: "contact_form",
    ...properties,
  });
}

export async function trackPricingViewed(properties: EventProperties = {}) {
  return trackEvent(EventName.CTA_PRICING_VIEWED, EventCategory.CTA, {
    ctaType: "pricing",
    ...properties,
  });
}

export async function trackPricingPlanSelected(
  planName: string,
  planPrice: number,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.CTA_PRICING_PLAN_SELECTED, EventCategory.CTA, {
    ctaType: "pricing_plan",
    planName,
    planPrice,
    ...properties,
  });
}

export async function trackFreeTrialClicked(properties: EventProperties = {}) {
  return trackEvent(EventName.CTA_FREE_TRIAL_CLICKED, EventCategory.CTA, {
    ctaType: "free_trial",
    ...properties,
  });
}

// ==================== FEATURE USAGE TRACKING ====================

export async function trackDashboardViewed(properties: EventProperties = {}) {
  return trackEvent(
    EventName.FEATURE_DASHBOARD_VIEWED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "dashboard",
      ...properties,
    },
  );
}

export async function trackAppointmentCreated(
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.FEATURE_APPOINTMENT_CREATED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "appointments",
      actionType: "create",
      ...properties,
    },
  );
}

export async function trackAppointmentCancelled(
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.FEATURE_APPOINTMENT_CANCELLED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "appointments",
      actionType: "cancel",
      ...properties,
    },
  );
}

export async function trackBillingViewed(properties: EventProperties = {}) {
  return trackEvent(
    EventName.FEATURE_BILLING_VIEWED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "billing",
      ...properties,
    },
  );
}

export async function trackSubscriptionUpgraded(
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.FEATURE_SUBSCRIPTION_UPGRADED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "subscription",
      actionType: "upgrade",
      ...properties,
    },
  );
}

export async function trackSubscriptionCancelled(
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.FEATURE_SUBSCRIPTION_CANCELLED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "subscription",
      actionType: "cancel",
      ...properties,
    },
  );
}

export async function trackSettingsUpdated(properties: EventProperties = {}) {
  return trackEvent(
    EventName.FEATURE_SETTINGS_UPDATED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "settings",
      actionType: "update",
      ...properties,
    },
  );
}

export async function trackTeamMemberInvited(properties: EventProperties = {}) {
  return trackEvent(
    EventName.FEATURE_TEAM_MEMBER_INVITED,
    EventCategory.FEATURE_USAGE,
    {
      featureName: "team",
      actionType: "invite",
      ...properties,
    },
  );
}

// ==================== USER JOURNEY TRACKING ====================

export async function trackSignupStarted(properties: EventProperties = {}) {
  return trackEvent(
    EventName.USER_SIGNUP_STARTED,
    EventCategory.USER_JOURNEY,
    properties,
  );
}

export async function trackSignupCompleted(
  userId: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.USER_SIGNUP_COMPLETED,
    EventCategory.USER_JOURNEY,
    {
      userId,
      ...properties,
    },
  );
}

export async function trackLoginSuccess(
  userId: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.USER_LOGIN_SUCCESS, EventCategory.USER_JOURNEY, {
    userId,
    ...properties,
  });
}

export async function trackLoginFailed(properties: EventProperties = {}) {
  return trackEvent(
    EventName.USER_LOGIN_FAILED,
    EventCategory.USER_JOURNEY,
    properties,
  );
}

export async function trackLogout(
  userId: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.USER_LOGOUT, EventCategory.USER_JOURNEY, {
    userId,
    ...properties,
  });
}

export async function trackOnboardingCompleted(
  userId: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.USER_ONBOARDING_COMPLETED,
    EventCategory.USER_JOURNEY,
    {
      userId,
      ...properties,
    },
  );
}

// ==================== ERROR TRACKING ====================

export async function trackFormValidationError(
  formName: string,
  errorMessage: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.ERROR_FORM_VALIDATION, EventCategory.ERROR, {
    formName,
    errorMessage,
    ...properties,
  });
}

export async function trackApiError(
  errorMessage: string,
  errorCode?: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.ERROR_API_REQUEST, EventCategory.ERROR, {
    errorMessage,
    errorCode,
    ...properties,
  });
}

export async function trackPaymentError(
  errorMessage: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.ERROR_PAYMENT_FAILED, EventCategory.ERROR, {
    errorMessage,
    ...properties,
  });
}

export async function trackPageNotFound(
  page: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.ERROR_PAGE_NOT_FOUND, EventCategory.ERROR, {
    page,
    ...properties,
  });
}

export async function trackSessionExpired(properties: EventProperties = {}) {
  return trackEvent(
    EventName.ERROR_SESSION_EXPIRED,
    EventCategory.ERROR,
    properties,
  );
}

// ==================== ENGAGEMENT TRACKING ====================

export async function trackVideoPlayed(
  videoId: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.ENGAGEMENT_VIDEO_PLAYED,
    EventCategory.ENGAGEMENT,
    {
      videoId,
      resourceType: "video",
      ...properties,
    },
  );
}

export async function trackResourceDownloaded(
  resourceId: string,
  resourceType: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.ENGAGEMENT_RESOURCE_DOWNLOADED,
    EventCategory.ENGAGEMENT,
    {
      resourceId,
      resourceType,
      ...properties,
    },
  );
}

export async function trackCaseStudyViewed(
  caseStudyId: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.ENGAGEMENT_CASE_STUDY_VIEWED,
    EventCategory.ENGAGEMENT,
    {
      caseStudyId,
      resourceType: "case_study",
      ...properties,
    },
  );
}

export async function trackFaqExpanded(
  faqId: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.ENGAGEMENT_FAQ_EXPANDED,
    EventCategory.ENGAGEMENT,
    {
      resourceId: faqId,
      resourceType: "faq",
      ...properties,
    },
  );
}

export async function trackChatbotOpened(properties: EventProperties = {}) {
  return trackEvent(
    EventName.ENGAGEMENT_CHATBOT_OPENED,
    EventCategory.ENGAGEMENT,
    {
      resourceType: "chatbot",
      ...properties,
    },
  );
}

// ==================== CONVERSION TRACKING ====================

export async function trackLeadCaptured(properties: EventProperties = {}) {
  return trackEvent(
    EventName.CONVERSION_LEAD_CAPTURED,
    EventCategory.CONVERSION,
    properties,
  );
}

export async function trackTrialStarted(
  userId: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.CONVERSION_TRIAL_STARTED,
    EventCategory.CONVERSION,
    {
      userId,
      ...properties,
    },
  );
}

export async function trackPaidCustomer(
  userId: string,
  value: number,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.CONVERSION_PAID_CUSTOMER,
    EventCategory.CONVERSION,
    {
      userId,
      value,
      ...properties,
    },
  );
}

// ==================== NAVIGATION TRACKING ====================

export async function trackPageView(
  page: string,
  properties: EventProperties = {},
) {
  return trackEvent(EventName.NAVIGATION_PAGE_VIEW, EventCategory.NAVIGATION, {
    page,
    ...properties,
  });
}

export async function trackExternalLinkClicked(
  destination: string,
  properties: EventProperties = {},
) {
  return trackEvent(
    EventName.NAVIGATION_EXTERNAL_LINK_CLICKED,
    EventCategory.NAVIGATION,
    {
      destination,
      ...properties,
    },
  );
}

// ==================== ANALYTICS QUERIES ====================
// DISABLED - Missing Prisma model (analytics_events)

/* DISABLED - Missing Prisma model analytics_events

/**
 * Get event count by category
 *
export async function getEventCountByCategory(
  startDate: Date,
  endDate: Date
): Promise<Record<EventCategory, number>> {
  const events = await prisma.analytics_events.groupBy({
    by: ['category'],
    where: {
      createdAt: {
        gte: startDate,
        lte: endDate,
      },
    },
    _count: {
      category: true,
    },
  });

  const result: Record<string, number> = {};
  for (const event of events) {
    result[event.category] = event._count.category;
  }

  return result as Record<EventCategory, number>;
}

/**
 * Get top events by count
 *
export async function getTopEvents(
  limit: number = 10,
  startDate?: Date,
  endDate?: Date
): Promise<Array<{ eventName: string; count: number }>> {
  const where = startDate && endDate ? {
    createdAt: {
      gte: startDate,
      lte: endDate,
    },
  } : {};

  const events = await prisma.analytics_events.groupBy({
    by: ['eventName'],
    where,
    _count: {
      eventName: true,
    },
    orderBy: {
      _count: {
        eventName: 'desc',
      },
    },
    take: limit,
  });

  return events.map(event => ({
    eventName: event.eventName,
    count: event._count.eventName,
  }));
}

/**
 * Get conversion funnel metrics
 *
export async function getConversionFunnel(
  startDate: Date,
  endDate: Date
): Promise<{
  signupStarted: number;
  signupCompleted: number;
  trialStarted: number;
  paidCustomer: number;
  conversionRates: {
    signupToTrial: number;
    trialToPaid: number;
    overallConversion: number;
  };
}> {
  const where = {
    createdAt: {
      gte: startDate,
      lte: endDate,
    },
  };

  const [signupStarted, signupCompleted, trialStarted, paidCustomer] = await Promise.all([
    prisma.analytics_events.count({
      where: {
        ...where,
        eventName: EventName.USER_SIGNUP_STARTED,
      },
    }),
    prisma.analytics_events.count({
      where: {
        ...where,
        eventName: EventName.USER_SIGNUP_COMPLETED,
      },
    }),
    prisma.analytics_events.count({
      where: {
        ...where,
        eventName: EventName.CONVERSION_TRIAL_STARTED,
      },
    }),
    prisma.analytics_events.count({
      where: {
        ...where,
        eventName: EventName.CONVERSION_PAID_CUSTOMER,
      },
    }),
  ]);

  return {
    signupStarted,
    signupCompleted,
    trialStarted,
    paidCustomer,
    conversionRates: {
      signupToTrial: signupCompleted > 0 ? (trialStarted / signupCompleted) * 100 : 0,
      trialToPaid: trialStarted > 0 ? (paidCustomer / trialStarted) * 100 : 0,
      overallConversion: signupStarted > 0 ? (paidCustomer / signupStarted) * 100 : 0,
    },
  };
}
*/
