import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import type { WawpDashboardData } from './types';
import { useNotices } from './hooks/useNotices';
import NoticeItem from './components/NoticeBar/NoticeItem';

interface NoticeBarProps {
  data?: WawpDashboardData;
}

const NoticeBar: React.FC<NoticeBarProps> = ({ data: propData }) => {
  const data = propData || window.wawpDashboardData;
  const notices = useNotices(data);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [direction, setDirection] = useState(0);
  const [isHovered, setIsHovered] = useState(false);

  // Handle slide changes
  const goToNext = useCallback(() => {
    if (!notices || notices.length <= 1) return;
    setDirection(1);
    setCurrentIndex((prev) => (prev + 1) % notices.length);
  }, [notices]);

  const goToPrev = useCallback(() => {
    if (!notices || notices.length <= 1) return;
    setDirection(-1);
    setCurrentIndex((prev) => (prev - 1 + notices.length) % notices.length);
  }, [notices]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowRight') goToNext();
      if (e.key === 'ArrowLeft') goToPrev();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [goToNext, goToPrev]);

  if (!data || notices.length === 0) return null;

  const variants = {
    enter: (direction: number) => ({
      x: direction > 0 ? 500 : -500,
      opacity: 0
    }),
    center: {
      zIndex: 1,
      x: 0,
      opacity: 1
    },
    exit: (direction: number) => ({
      zIndex: 0,
      x: direction < 0 ? 500 : -500,
      opacity: 0
    })
  };

  const swipeConfidenceThreshold = 10000;
  const swipePower = (offset: number, velocity: number) => {
    return Math.abs(offset) * velocity;
  };

  return (
    <div 
      className="wawp-notices-container relative z-[9999] pointer-events-auto" 
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      style={{ 
        marginBottom: '10px', 
        width: '100%',
        padding: 0,
        boxSizing: 'border-box'
      }}
    >
      <div className="wawp-notices-wrapper relative group">
        
        {/* Slider Navigation Arrows */}
        {notices.length > 1 && (
          <div style={{ 
            opacity: isHovered ? 1 : 0.3, 
            transition: 'opacity 0.3s ease',
            pointerEvents: 'auto'
          }}>
            <div 
              onClick={(e) => { e.stopPropagation(); goToPrev(); }}
              style={{
                position: 'absolute',
                left: '-35px', 
                top: '50%',
                transform: 'translateY(-50%)',
                zIndex: 50,
                width: '32px',
                height: '32px',
                borderRadius: '50%',
                background: 'white',
                border: '1px solid #e2e8f0',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
                transition: 'all 0.2s ease',
                color: '#64748b'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = '#f8fafc';
                e.currentTarget.style.color = '#004449';
                e.currentTarget.style.transform = 'translateY(-50%) scale(1.1)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'white';
                e.currentTarget.style.color = '#64748b';
                e.currentTarget.style.transform = 'translateY(-50%) scale(1)';
              }}
            >
              <i className="ri-arrow-left-s-line" style={{ fontSize: '20px' }}></i>
            </div>
            <div 
              onClick={(e) => { e.stopPropagation(); goToNext(); }}
              style={{
                position: 'absolute',
                right: '-35px', 
                top: '50%',
                transform: 'translateY(-50%)',
                zIndex: 50,
                width: '32px',
                height: '32px',
                borderRadius: '50%',
                background: 'white',
                border: '1px solid #e2e8f0',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
                transition: 'all 0.2s ease',
                color: '#64748b'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = '#f8fafc';
                e.currentTarget.style.color = '#004449';
                e.currentTarget.style.transform = 'translateY(-50%) scale(1.1)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'white';
                e.currentTarget.style.color = '#64748b';
                e.currentTarget.style.transform = 'translateY(-50%) scale(1)';
              }}
            >
              <i className="ri-arrow-right-s-line" style={{ fontSize: '20px' }}></i>
            </div>

            {/* Pagination Dots */}
            <div style={{
              position: 'absolute',
              bottom: '-22px', 
              left: '50%',
              transform: 'translateX(-50%)',
              display: 'flex',
              gap: '6px',
              zIndex: 10
            }}>
              {notices.map((_, i) => (
                <div 
                  key={i}
                  onClick={() => {
                    setDirection(i > currentIndex ? 1 : -1);
                    setCurrentIndex(i);
                  }}
                  style={{
                    width: i === currentIndex ? '16px' : '6px',
                    height: '6px',
                    borderRadius: '3px',
                    background: i === currentIndex ? '#64748b' : '#cbd5e1',
                    cursor: 'pointer',
                    transition: 'all 0.3s ease'
                  }}
                />
              ))}
            </div>
          </div>
        )}

        <div 
          className="wawp-notices-slider overflow-hidden relative" 
          style={{ 
            borderRadius: '12px',
            border: 'none',
            minHeight: '80px'
          }}
        >
          <AnimatePresence initial={false} custom={direction} mode="wait">
            <motion.div
              key={currentIndex}
              custom={direction}
              variants={variants}
              initial="enter"
              animate="center"
              exit="exit"
              transition={{
                x: { type: "spring", stiffness: 300, damping: 30 },
                opacity: { duration: 0.2 }
              }}
              drag="x"
              dragConstraints={{ left: 0, right: 0 }}
              dragElastic={1}
              onDragEnd={(_, { offset, velocity }) => {
                const swipe = swipePower(offset.x, velocity.x);
                if (swipe < -swipeConfidenceThreshold) {
                  goToNext();
                } else if (swipe > swipeConfidenceThreshold) {
                  goToPrev();
                }
              }}
              className="w-full h-full cursor-grab active:cursor-grabbing"
            >
              <NoticeItem notice={notices[currentIndex]} />
            </motion.div>
          </AnimatePresence>
        </div>
      </div>
    </div>
  );
};

export default NoticeBar;
