import { useEffect, useRef, useCallback } from 'react';
import { Button, Typography, theme } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { getOrCreateSessionId } from '@/lib/media-public-api';
import type { GalleryAd } from '@/types/gallery-ads';

const { Title, Text } = Typography;


interface GalleryAdCardProps {
  ad: GalleryAd;
  /** When true, disables tracking and click navigation (for admin preview) */
  preview?: boolean;
}

export default function GalleryAdCard({ ad, preview }: GalleryAdCardProps) {
  const { token } = theme.useToken();
  const navigate = useNavigate();
  const cardRef = useRef<HTMLDivElement>(null);
  const impressionSent = useRef(false);

  // IntersectionObserver for impression tracking: fires when 50%+ visible for 1s
  useEffect(() => {
    if (preview) return; // No tracking in preview mode

    const el = cardRef.current;
    if (!el || impressionSent.current) return;

    let timer: ReturnType<typeof setTimeout> | null = null;

    const observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (entry?.isIntersecting) {
          timer = setTimeout(() => {
            if (!impressionSent.current) {
              impressionSent.current = true;
              trackEvent('impression');
            }
          }, 1000);
        } else if (timer) {
          clearTimeout(timer);
          timer = null;
        }
      },
      { threshold: 0.5 }
    );

    observer.observe(el);

    return () => {
      observer.disconnect();
      if (timer) clearTimeout(timer);
    };
  }, [ad.id, preview]);

  const trackEvent = useCallback(
    (event: 'impression' | 'click') => {
      if (preview) return;
      axios
        .post('/api/gallery-ads/track', {
          adId: ad.id,
          event,
          sessionId: getOrCreateSessionId(),
        })
        .catch(() => {}); // silent fail
    },
    [ad.id, preview]
  );

  const handleClick = () => {
    if (preview) return; // No navigation in preview mode
    trackEvent('click');
    if (ad.linkUrl) {
      if (ad.linkUrl.startsWith('http')) {
        window.open(ad.linkUrl, '_blank', 'noopener');
      } else {
        navigate(ad.linkUrl);
      }
    }
  };

  // Variant-specific styles
  const isHighlight = ad.variant === 'highlight';
  const isMinimal = ad.variant === 'minimal';

  const bgGradient = ad.bgColor
    ? `linear-gradient(135deg, ${ad.bgColor} 0%, ${adjustColor(ad.bgColor, -30)} 100%)`
    : isHighlight
      ? `linear-gradient(135deg, ${token.colorPrimary} 0%, ${adjustColor(token.colorPrimary, -40)} 100%)`
      : `linear-gradient(135deg, ${token.colorBgElevated} 0%, ${token.colorBgContainer} 100%)`;

  const borderStyle = isHighlight
    ? `2px solid ${ad.bgColor || token.colorPrimary}`
    : `1px solid ${token.colorBorderSecondary}`;

  return (
    <div
      ref={cardRef}
      style={{
        borderRadius: 12,
        overflow: 'hidden',
        border: borderStyle,
        cursor: preview ? 'default' : ad.linkUrl ? 'pointer' : 'default',
        transition: 'all 0.2s ease',
        display: 'flex',
        flexDirection: 'column',
        ...(isHighlight && {
          boxShadow: `0 0 20px ${(ad.bgColor || token.colorPrimary)}33`,
        }),
      }}
      onClick={handleClick}
    >
      {/* Top section: visual area matching video card 16:9 ratio */}
      {!isMinimal && (
        <div
          style={{
            position: 'relative',
            paddingTop: '56.25%', // 16:9
            background: ad.imagePath ? `url(${ad.imagePath}) center/cover no-repeat` : bgGradient,
          }}
        >
          {/* Overlay content centered in the 16:9 space */}
          <div
            style={{
              position: 'absolute',
              inset: 0,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              padding: 20,
              textAlign: 'center',
              ...(ad.imagePath && {
                background: 'rgba(0, 0, 0, 0.5)',
              }),
            }}
          >
            {ad.iconEmoji && (
              <span style={{ fontSize: 36, marginBottom: 8 }}>{ad.iconEmoji}</span>
            )}
            <Title
              level={4}
              style={{
                color: '#fff',
                margin: 0,
                textShadow: '0 1px 3px rgba(0,0,0,0.3)',
              }}
            >
              {ad.title}
            </Title>
            {ad.subtitle && (
              <Text
                style={{
                  color: 'rgba(255,255,255,0.85)',
                  marginTop: 8,
                  fontSize: 13,
                  maxWidth: 240,
                }}
              >
                {ad.subtitle}
              </Text>
            )}
          </div>
        </div>
      )}

      {/* Bottom section: CTA + promoted label */}
      <div
        style={{
          padding: isMinimal ? '20px 16px' : '12px 16px',
          background: isMinimal ? bgGradient : token.colorBgContainer,
          display: 'flex',
          flexDirection: 'column',
          gap: 8,
        }}
      >
        {isMinimal && (
          <>
            {ad.iconEmoji && (
              <span style={{ fontSize: 24 }}>{ad.iconEmoji}</span>
            )}
            <Title
              level={5}
              style={{ color: token.colorText, margin: 0 }}
            >
              {ad.title}
            </Title>
            {ad.subtitle && (
              <Text type="secondary" style={{ fontSize: 12 }}>
                {ad.subtitle}
              </Text>
            )}
          </>
        )}

        {ad.ctaText && (
          <Button
            type={ad.ctaStyle === 'primary' ? 'primary' : ad.ctaStyle === 'outline' ? 'default' : 'link'}
            size="small"
            block={!isMinimal}
            onClick={(e) => {
              e.stopPropagation();
              handleClick();
            }}
          >
            {ad.ctaText}
          </Button>
        )}

        <Text
          style={{
            fontSize: 10,
            color: token.colorTextQuaternary,
            textAlign: 'center',
          }}
        >
          Promoted
        </Text>
      </div>
    </div>
  );
}

/** Lighten/darken a hex color by an amount (-255 to 255) */
function adjustColor(hex: string, amount: number): string {
  const clamp = (v: number) => Math.max(0, Math.min(255, v));
  const h = hex.replace('#', '');
  const r = clamp(parseInt(h.substring(0, 2), 16) + amount);
  const g = clamp(parseInt(h.substring(2, 4), 16) + amount);
  const b = clamp(parseInt(h.substring(4, 6), 16) + amount);
  return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
}
