"use client";

import { useState, useEffect, useRef } from "react";
import { useGetHomeAiCarouselList } from "@/hooks/useHome";
import AIStandardCard from "@/components/features/ai-standard-card";

const HeaderSlide = () => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const transitionLockRef = useRef(false);
  
  const { data, isLoading } = useGetHomeAiCarouselList();
  const characters = (data || []).map(item => ({
    ...item,
    likedNum: item.likedCount || 0,
  }));

  const handleNext = () => {
    if (transitionLockRef.current || characters.length === 0) return;
    transitionLockRef.current = true;
    setIsTransitioning(true);
    setActiveIndex((prev) => (prev + 1) % characters.length);
    setTimeout(() => {
      setIsTransitioning(false);
      transitionLockRef.current = false;
    }, 300);
  };

  const handlePrev = () => {
    if (transitionLockRef.current || characters.length === 0) return;
    transitionLockRef.current = true;
    setIsTransitioning(true);
    setActiveIndex((prev) => (prev - 1 + characters.length) % characters.length);
    setTimeout(() => {
      setIsTransitioning(false);
      transitionLockRef.current = false;
    }, 300);
  };

  // 自动轮播
  useEffect(() => {
    if (isPaused || characters.length === 0) return;

    const interval = setInterval(() => {
      handleNext();
    }, 4000);

    return () => clearInterval(interval);
  }, [isPaused, characters.length]);

  const handleSlideClick = (index: number) => {
    if (isTransitioning || characters.length === 0) return;
    
    const currentIndex = activeIndex;
    
    // 如果点击的是中间的卡片，不做任何操作
    if (index === currentIndex) return;
    
    // 计算点击的卡片相对于中心的位置
    const totalSlides = characters.length;
    let diff = index - currentIndex;
    
    // 处理循环边界情况，找到最短路径
    if (diff > totalSlides / 2) {
      diff = diff - totalSlides;
    } else if (diff < -totalSlides / 2) {
      diff = diff + totalSlides;
    }
    
    // 点击左侧向右滑动（prev），点击右侧向左滑动（next）
    if (diff < 0) {
      handlePrev();
    } else if (diff > 0) {
      handleNext();
    }
  };

  // 计算每张卡片的样式
  const getCardStyle = (index: number) => {
    const totalSlides = characters.length;
    let position = index - activeIndex;
    
    // 处理循环
    if (position > totalSlides / 2) {
      position = position - totalSlides;
    } else if (position < -totalSlides / 2) {
      position = position + totalSlides;
    }
    
    // 只显示 -2 到 2 的位置（共5张卡片）
    const isVisible = Math.abs(position) <= 2;
    
    // 计算样式参数 - 让卡片更紧密地叠在一起
    const scale = position === 0 ? 1 : 1 - Math.abs(position) * 0.16;
    // 第二张和第四张卡片（position = ±1）向外移动更多，第一张和第五张（position = ±2）保持原位
    const translateX = position === 0 ? 0 : 
                       Math.abs(position) === 1 ? position * 160 : // 第二、四张卡片向外移动更多
                       position * 120; // 第一、五张卡片保持原间距
    const opacity = 1; // 两边卡片更透明
    const zIndex = 10 - Math.abs(position);
    
    return {
      transform: `translateX(${translateX}px) scale(${scale})`,
      opacity: isVisible ? opacity : 0,
      zIndex,
      pointerEvents: isVisible ? ('auto' as const) : ('none' as const),
      transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
    };
  };

  if (isLoading) {
    return null;
  }

  return (
    <div 
      className="w-full py-10"
      style={{ height: '400px' }}
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      <div className="relative h-full w-full">
        <div className="absolute inset-0 flex items-center justify-center">
          {characters.map((character, index) => {
            const position = (() => {
              const totalSlides = characters.length;
              let pos = index - activeIndex;
              if (pos > totalSlides / 2) {
                pos = pos - totalSlides;
              } else if (pos < -totalSlides / 2) {
                pos = pos + totalSlides;
              }
              return pos;
            })();
            
            const isCenter = position === 0;
            const isVisible = Math.abs(position) <= 2;
            
            return (
              <div
                key={character.aiId || index}
                className="absolute"
                style={{
                  ...getCardStyle(index),
                  width: isCenter ? '240px' : '240px',
                  height: isCenter ? '320px' : '320px',
                }}
              >
                {!isCenter ? (
                  <div
                    className="cursor-pointer h-full"
                    onClick={() => handleSlideClick(index)}
                  >
                    <div 
                      className="[&_.txt-headline-s]:hidden [&_.txt-label-s]:hidden [&_[class*='Tag']]:hidden [&_a]:pointer-events-none [&_a]:cursor-default [&_[class*='absolute'][class*='bottom']]:!hidden [&_[class*='backdrop-blur']]:!hidden h-full"
                    >
                      <AIStandardCard character={character} disableHover={true} />
                    </div>
                  </div>
                ) : (
                  <div className="h-full">
                    <AIStandardCard character={character} disableHover={true} />
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default HeaderSlide;