'use client';

import clsx from 'clsx';
import { useRouter } from 'next/navigation';
import React, { useCallback, useContext, useState } from 'react';
import { twMerge } from 'tailwind-merge';

import CollapsibleBanner from '@/components/banner/CollapsibleBanner';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { HeroCarouselContext } from '@/components/promos/HeroCarousel';
import SimpleVideoPlayer from '@/components/video/SimpleVideoPlayer';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import { ChevronDownIcon, ChevronUpIcon } from '@/icons';
import {
  BannerCTA,
  BannerWebItem,
  HeroBackgroundAlignment,
} from '@/types/bannerTypes';

import { BannerCTAs } from './BannerCTAs';
import { BannerTiles } from './BannerTiles';
import HeroBanner from './HeroBanner';

export interface BannerContentProps {
  bannerItem: BannerWebItem;
  collapsed?: boolean;
  onCollapseChange?: (collapsed: boolean) => void;
  className?: string;
}

export const BannerContent: React.FC<BannerContentProps> = React.memo(
  ({ bannerItem, collapsed, onCollapseChange, className }) => {
    const {
      titleText: { text: titleText, color: titleColor } = {},
      subtitleText: { text: subtitleText, color: subtitleColor } = {},
      collapsedContent: {
        titleText: { text: collapsedTitleText } = {},
        subtitleText: { text: collapsedSubtitleText } = {},
      } = {},
      primaryCta,
      secondaryCta,
      heroBackgroundImgUrl,
      heroBackgroundVideoUrl,
      heroBackgroundOverlay = 'gradient',
      heroBackgroundAlignment = HeroBackgroundAlignment.Center,
      heroBackgroundImgUrlMobile,
      // TODO: disabling video background on mobile for v5 launch
      // heroBackgroundVideoUrlMobile = heroBackgroundVideoUrl,
      heroBackgroundOverlayMobile = heroBackgroundOverlay,
      heroBackgroundAlignmentMobile = heroBackgroundAlignment,
      heroBackgroundColor,
      tag: {
        text: { text: tagText, color: tagForegroundColor } = {},
        color: tagBackgroundColor,
      } = {},
    } = bannerItem;

    const router = useRouter();

    // Handle CTA click - used by both banner click and button clicks
    const handleCTAClick = useCallback(
      (cta: BannerCTA, _isPrimary: boolean) => {
        // Log analytics event if needed
        // logWebUserEvent({
        //   actionName: _isPrimary
        //     ? 'BannerPrimaryCTAClicked'
        //     : 'BannerSecondaryCTAClicked',
        //   principalObjectType: 'banner_cta',
        //   principalObjectValue: cta.action,
        //   context: {
        //     ctaText: cta.text.text,
        //     ctaUrl: cta.url,
        //     ctaAction: cta.action,
        //   },
        // });

        // Handle navigation
        if (cta.url) {
          if (cta.url.startsWith('http')) {
            window.open(cta.url, '_blank');
          } else if (cta.url.startsWith('/studio')) {
            window.location.href = cta.url;
          } else {
            router.push(cta.url);
          }
        }
      },
      [router]
    );

    // Handle banner click - triggers primary CTA
    const handleBannerClick = useCallback(() => {
      if (primaryCta) {
        handleCTAClick(primaryCta, true);
      }
    }, [primaryCta, handleCTAClick]);

    const {
      isCollapsed: contextIsCollapsed,
      setIsCollapsed: contextSetIsCollapsed,
    } = useContext(HeroCarouselContext);

    const isMobile = !useBreakpointMd();

    // Use external props if provided, otherwise fall back to context
    const isCollapsed =
      collapsed !== undefined ? collapsed : contextIsCollapsed;
    const setIsCollapsed =
      onCollapseChange !== undefined ? onCollapseChange : contextSetIsCollapsed;

    // TODO: disabling video background on mobile for v5 launch
    const backgroundVideoUrl = isMobile
      ? // ? (heroBackgroundVideoUrlMobile ?? heroBackgroundVideoUrl)
        undefined
      : heroBackgroundVideoUrl;
    const backgroundImageUrl = isMobile
      ? (heroBackgroundImgUrlMobile ?? heroBackgroundImgUrl)
      : heroBackgroundImgUrl;
    const backgroundAlignment = isMobile
      ? heroBackgroundAlignmentMobile
      : heroBackgroundAlignment;
    const needsOverlay = !!(backgroundImageUrl || backgroundVideoUrl);
    const backgroundOverlay = !needsOverlay
      ? 'none'
      : isMobile
        ? heroBackgroundOverlayMobile || heroBackgroundOverlay
        : heroBackgroundOverlay || heroBackgroundOverlayMobile;

    const [[videoWidth, videoHeight], setVideoDimensions] = useState([0, 0]);
    const handleLoadedVideoMetadata = useCallback((e: Event) => {
      if (e.target instanceof HTMLVideoElement) {
        const video = e.target;
        setVideoDimensions([video.videoWidth, video.videoHeight]);
      }
    }, []);

    const bannerStyles = {
      '--banner-title-foreground': titleColor,
      '--banner-subtitle-foreground': subtitleColor,
      '--banner-background': heroBackgroundColor,
      '--banner-background-image':
        backgroundImageUrl && `url('${backgroundImageUrl}')`,
      '--banner-tag-foreground': tagForegroundColor,
      '--banner-tag-background': tagBackgroundColor,
      '--banner-video-aspect':
        videoWidth && videoHeight ? `${videoWidth}/${videoHeight}` : undefined,
    } as React.CSSProperties;

    const bannerLeftSection = (
      <div className='relative flex flex-col items-center justify-end gap-2 md:max-w-[400px] md:items-start'>
        <div className='w-full'>
          {titleText && (
            <h2 className='mb-4 font-serif text-[36px] leading-[1.2] font-light text-(--banner-title-foreground,var(--color-foreground-primary)) max-md:text-center md:text-[40px]'>
              {titleText.split('\n').map((line, i) => (
                <span key={i}>
                  {i > 0 && <br />}
                  {line}
                </span>
              ))}
            </h2>
          )}
          {subtitleText && (
            <div className='font-sans text-[14px] leading-[16px] font-normal text-(--banner-subtitle-foreground,var(--color-foreground-tertiary)) max-md:text-center'>
              {subtitleText.split('\n\n').map((line, i) => (
                <p className='mb-3' key={i}>
                  {line}
                </p>
              ))}
            </div>
          )}

          <div className='mt-4 hidden gap-2 md:flex'>
            <BannerCTAs
              primaryCTA={primaryCta}
              secondaryCTA={secondaryCta}
              buttonSize={ButtonSize.Mini}
              secondaryVariant={ButtonVariant.Glass}
              onCTAClick={handleCTAClick}
            />
          </div>
        </div>
      </div>
    );

    const bannerRightSection = (
      <div>
        <BannerTiles tiles={bannerItem.tiles ?? []} />
        <div className='my-4 flex justify-center gap-2 md:hidden'>
          <BannerCTAs
            primaryCTA={primaryCta}
            secondaryCTA={secondaryCta}
            buttonSize={ButtonSize.Small}
            secondaryVariant={ButtonVariant.Secondary}
            onCTAClick={handleCTAClick}
          />
        </div>
      </div>
    );

    return (
      <CollapsibleBanner
        className={twMerge(
          'theme-dark relative min-h-full rounded-2xl bg-linear-to-r from-background-secondary to-background-primary',
          className
        )}
        style={bannerStyles}
        collapsed={isCollapsed}
        onCollapse={setIsCollapsed}
        persistentContent={({ onToggle, isCollapsed }) => (
          <>
            {isCollapsed ? null : (
              <div
                className={twMerge(
                  clsx(
                    'absolute inset-0 overflow-clip bg-(--banner-background,var(--color-background-primary)) bg-cover bg-center transition-opacity duration-500 ease-in-out will-change-[opacity]',
                    'bg-(image:--banner-background-image,none)',
                    {
                      /**
                       * Background image position/size overrides
                       *
                       * Default is centered and scale-to-cover
                       */
                      'bg-left':
                        backgroundAlignment === HeroBackgroundAlignment.Left,
                      'bg-right':
                        backgroundAlignment === HeroBackgroundAlignment.Right,
                      'bg-top':
                        backgroundAlignment === HeroBackgroundAlignment.Top,
                      'bg-bottom':
                        backgroundAlignment === HeroBackgroundAlignment.Bottom,
                      'bg-bottom-left':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.BottomLeft,
                      'bg-bottom-right':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.BottomRight,
                      'bg-top-left':
                        backgroundAlignment === HeroBackgroundAlignment.TopLeft,
                      'bg-top-right':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.TopRight,
                      // Repeating
                      'bg-size-[auto_100%] bg-left':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.LeftRepeatX,
                      'bg-size-[auto_100%] bg-center':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.CenterRepeatX,
                      'bg-size-[auto_100%] bg-right':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.RightRepeatX,
                      'bg-size-[100%_auto] bg-top':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.TopRepeatY,
                      'bg-size-[100%_auto] bg-center':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.CenterRepeatY,
                      'bg-size-[100%_auto] bg-bottom':
                        backgroundAlignment ===
                        HeroBackgroundAlignment.BottomRepeatY,
                      /**
                       * Background overlay
                       */
                      'after:absolute after:inset-0 after:bg-gradient-to-r after:from-opacity-black-60 after:to-opacity-black-20 max-md:after:bg-gradient-to-t':
                        backgroundOverlay === 'gradient',
                      'after:absolute after:inset-0 after:bg-linear-30 after:from-background-primary-dark after:from-20% after:to-transparent after:to-60%':
                        backgroundOverlay === 'minimal_gradient',
                    }
                  )
                )}
              >
                {backgroundVideoUrl && (
                  <SimpleVideoPlayer
                    className={clsx(
                      'pointer-events-none absolute object-cover',
                      'inset-0 aspect-(--banner-video-aspect) min-h-full min-w-full',
                      {
                        'object-left':
                          backgroundAlignment === HeroBackgroundAlignment.Left,
                        'object-left-top':
                          backgroundAlignment ===
                          HeroBackgroundAlignment.TopLeft,
                        'object-left-bottom':
                          backgroundAlignment ===
                          HeroBackgroundAlignment.BottomLeft,
                        'object-right':
                          backgroundAlignment === HeroBackgroundAlignment.Right,
                        'object-right-top':
                          backgroundAlignment ===
                          HeroBackgroundAlignment.TopRight,
                        'object-right-bottom':
                          backgroundAlignment ===
                          HeroBackgroundAlignment.BottomRight,
                        'object-top':
                          backgroundAlignment === HeroBackgroundAlignment.Top,
                        'object-bottom':
                          backgroundAlignment ===
                          HeroBackgroundAlignment.Bottom,
                        'object-center':
                          backgroundAlignment ===
                          HeroBackgroundAlignment.Center,
                      }
                    )}
                    url={backgroundVideoUrl}
                    muted
                    loop
                    playsInline
                    preload='auto'
                    playing={!isCollapsed}
                    onLoadedMetadata={handleLoadedVideoMetadata}
                  />
                )}
              </div>
            )}

            <div className='relative z-10 flex items-center justify-between gap-4 p-4'>
              <div className='flex min-w-0 flex-1 items-center gap-4 px-2'>
                {tagText && (
                  <div className='inline-block rounded-full bg-(--banner-tag-background) px-2 py-0.5 text-[12px] leading-[16px] font-medium text-(--banner-tag-foreground) uppercase'>
                    {tagText}
                  </div>
                )}
                <div className='min-w-0 flex-1'>
                  {isCollapsed &&
                  (collapsedTitleText || collapsedSubtitleText) ? (
                    <div className='flex flex-row items-center gap-2'>
                      <h2 className='font-sans text-[16px] leading-[16px] font-medium text-foreground-primary'>
                        {collapsedTitleText}
                      </h2>
                      <p className='hidden font-sans text-[14px] leading-[20px] font-normal text-foreground-tertiary xl:block'>
                        {collapsedSubtitleText}
                      </p>
                    </div>
                  ) : null}
                </div>
              </div>
              <Button
                variant={ButtonVariant.Tertiary}
                shape={ButtonShape.Pill}
                size={ButtonSize.Small}
                icon={isCollapsed ? ChevronDownIcon : ChevronUpIcon}
                onClick={onToggle}
                aria-label={isCollapsed ? 'Expand banner' : 'Collapse banner'}
                aspectSquare
              />
            </div>
          </>
        )}
        collapsedContent={() => null}
        expandedContent={() => (
          <div
            onClick={handleBannerClick}
            className={clsx('cursor-pointer', {
              'pointer-events-none': !primaryCta?.url,
            })}
            role='button'
            tabIndex={primaryCta?.url ? 0 : -1}
            onKeyDown={(e) => {
              if (primaryCta?.url && (e.key === 'Enter' || e.key === ' ')) {
                e.preventDefault();
                handleBannerClick();
              }
            }}
          >
            <HeroBanner
              leftSection={bannerLeftSection}
              rightSection={bannerRightSection}
            />
          </div>
        )}
      />
    );
  }
);

BannerContent.displayName = 'BannerContent';
