'use client';

import { useGateValue, useStatsigClient } from '@statsig/react-bindings';
import { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import logWebUserEvent from '@/logging/logWebUserEvent';

import NotificationBanner from './NotificationBanner';

interface NotificationBannerConfig {
  web?: {
    type: string;
    id: string;
    feature_gate: string;
    tag: {
      text: {
        text: string;
        key?: string;
        color?: string;
      };
      color: string;
    };
    title_text: {
      text: string;
      color: string;
    };
    subtitle_text: {
      text: string;
      color: string;
    };
  };
  ios?: any;
  android?: any;
}

const NotificationBannerContainer: React.FC = () => {
  const { session } = useStores();
  const statsigClient = useStatsigClient();
  const [bannerConfig, setBannerConfig] =
    useState<NotificationBannerConfig | null>(null);
  const [hasLoggedDisplay, setHasLoggedDisplay] = useState(false);

  // Load the dynamic config
  useEffect(() => {
    if (statsigClient?.client?.loadingStatus === 'Ready') {
      const config = statsigClient.getDynamicConfig(
        'notifications-banner-config'
      );
      const configContent = config.value as NotificationBannerConfig;
      setBannerConfig(configContent);
    }
  }, [statsigClient, statsigClient?.client?.loadingStatus]);

  // Check if web config exists and get the feature gate
  const webConfig = bannerConfig?.web;
  const isFeatureEnabled = useGateValue(webConfig?.feature_gate || '');

  // Check if banner has been dismissed using sessionStore
  const bannerId = webConfig?.id;
  const isDismissed = bannerId ? session.isBannerDismissed(bannerId) : false;

  // Log banner display (only once per session)
  useEffect(() => {
    if (webConfig && isFeatureEnabled && !isDismissed && !hasLoggedDisplay) {
      logWebUserEvent({
        actionName: 'NotificationBannerDisplayed',
        context: {
          bannerId: webConfig.id,
          ...(webConfig.feature_gate && {
            featureGate: webConfig.feature_gate,
          }),
        },
      });
      setHasLoggedDisplay(true);
    }
  }, [webConfig, isFeatureEnabled, isDismissed, hasLoggedDisplay]);

  // Handle banner dismissal using sessionStore
  const handleDismiss = async () => {
    if (bannerId) {
      try {
        // Log dismissal before updating state
        logWebUserEvent({
          actionName: 'NotificationBannerDismissed',
          context: {
            bannerId,
            ...(webConfig?.feature_gate && {
              featureGate: webConfig.feature_gate,
            }),
          },
        });

        await session.dismissBanner(bannerId);
      } catch (error) {
        console.error('Failed to dismiss banner:', error);
      }
    }
  };

  if (!webConfig || !isFeatureEnabled || isDismissed) {
    return null;
  }

  return (
    <NotificationBanner
      label={webConfig.tag.text.text}
      header={webConfig.title_text.text}
      subheader={webConfig.subtitle_text.text}
      onDismiss={handleDismiss}
      defaultOpen={true}
    />
  );
};

export default NotificationBannerContainer;
