'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { 
  Package, 
  ArrowLeft,
  X,
  ChevronLeft,
  ChevronRight,
  ZoomIn,
  ImageIcon,
  Loader2
} from 'lucide-react';
import { useLanguage } from '@/i18n/LanguageContext';
import { LanguageSwitcherSimple } from '@/components/language-switcher';

interface Case {
  id: string;
  title: string;
  description: string | null;
  images: string[];
  category: string | null;
  created_at: string;
}

export default function CasesPage() {
  const { t, locale } = useLanguage();
  const [cases, setCases] = useState<Case[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedCase, setSelectedCase] = useState<Case | null>(null);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [showLightbox, setShowLightbox] = useState(false);

  useEffect(() => {
    const fetchCases = async () => {
      try {
        const response = await fetch('/api/cases');
        const data = await response.json();
        if (response.ok) {
          setCases(data.cases || []);
        }
      } catch (error) {
        console.error('Error fetching cases:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchCases();
  }, []);

  // 打开灯箱查看图片
  const openLightbox = (caseItem: Case, imageIndex: number) => {
    setSelectedCase(caseItem);
    setCurrentImageIndex(imageIndex);
    setShowLightbox(true);
  };

  // 关闭灯箱
  const closeLightbox = () => {
    setShowLightbox(false);
    setSelectedCase(null);
  };

  // 上一张图片
  const prevImage = () => {
    if (selectedCase) {
      setCurrentImageIndex((prev) => 
        prev === 0 ? selectedCase.images.length - 1 : prev - 1
      );
    }
  };

  // 下一张图片
  const nextImage = () => {
    if (selectedCase) {
      setCurrentImageIndex((prev) => 
        prev === selectedCase.images.length - 1 ? 0 : prev + 1
      );
    }
  };

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!showLightbox) return;
      
      if (e.key === 'Escape') closeLightbox();
      if (e.key === 'ArrowLeft') prevImage();
      if (e.key === 'ArrowRight') nextImage();
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [showLightbox, selectedCase]);

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white pt-20">
      {/* 导航栏 */}
      <nav className="fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center gap-3">
              <Link href="/" className="flex items-center gap-3">
                <div className="w-11 h-11 bg-white rounded-xl flex items-center justify-center shadow-lg border border-gray-100">
                  <img src="/images/logo.png" alt={t.common.logo} className="w-9 h-9 object-contain" />
                </div>
                <div>
                  <h1 className="text-lg font-bold bg-gradient-to-r from-blue-600 to-indigo-700 bg-clip-text text-transparent">{t.common.logo}</h1>
                  <p className="text-xs text-gray-400 font-medium tracking-wide">{t.common.logoSub}</p>
                </div>
              </Link>
            </div>
            <div className="flex items-center gap-3">
              <LanguageSwitcherSimple />
              <Link 
                href="/" 
                className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-blue-600 transition-colors text-sm"
              >
                <ArrowLeft className="w-4 h-4" />
                {t.nav.home}
              </Link>
            </div>
          </div>
        </div>
      </nav>

      {/* 页面内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* 页面标题 */}
        <div className="text-center mb-12">
          <h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-4">{t.cases.title}</h1>
          <p className="text-gray-500 max-w-2xl mx-auto">
            {t.cases.subtitle}
          </p>
        </div>

        {/* 案例列表 */}
        {isLoading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
          </div>
        ) : cases.length === 0 ? (
          <div className="text-center py-20">
            <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <ImageIcon className="w-10 h-10 text-gray-400" />
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">{t.cases.noCases}</h3>
            <p className="text-gray-500">{t.cases.noCasesDesc}</p>
          </div>
        ) : (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {cases.map((caseItem) => (
              <div 
                key={caseItem.id}
                className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 group"
              >
                {/* 图片区域 */}
                <div className="relative aspect-video bg-gray-100">
                  {caseItem.images.length > 0 ? (
                    <>
                      <img 
                        src={caseItem.images[0]} 
                        alt={caseItem.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                      {caseItem.images.length > 1 && (
                        <div className="absolute bottom-3 right-3 bg-black/60 text-white text-xs px-2 py-1 rounded-full">
                          +{caseItem.images.length - 1} {t.cases.images}
                        </div>
                      )}
                      <div 
                        className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center cursor-pointer"
                        onClick={() => openLightbox(caseItem, 0)}
                      >
                        <ZoomIn className="w-8 h-8 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
                      </div>
                    </>
                  ) : (
                    <div className="flex items-center justify-center h-full">
                      <ImageIcon className="w-12 h-12 text-gray-300" />
                    </div>
                  )}
                </div>

                {/* 内容区域 */}
                <div className="p-5">
                  <h3 className="text-lg font-semibold text-gray-900 mb-2 line-clamp-1">
                    {caseItem.title}
                  </h3>
                  {caseItem.description && (
                    <p className="text-gray-500 text-sm line-clamp-2 mb-3">
                      {caseItem.description}
                    </p>
                  )}
                  <div className="flex items-center justify-between">
                    {caseItem.category && (
                      <span className="inline-flex items-center px-2.5 py-1 bg-blue-50 text-blue-600 text-xs font-medium rounded-full">
                        {caseItem.category}
                      </span>
                    )}
                    <button 
                      onClick={() => openLightbox(caseItem, 0)}
                      className="text-sm text-blue-600 hover:text-blue-700 font-medium"
                    >
                      {t.cases.viewImages} →
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 图片灯箱 */}
      {showLightbox && selectedCase && (
        <div 
          className="fixed inset-0 z-50 bg-black/95 flex items-center justify-center"
          onClick={closeLightbox}
        >
          {/* 关闭按钮 */}
          <button 
            onClick={closeLightbox}
            className="absolute top-4 right-4 z-10 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors"
          >
            <X className="w-6 h-6" />
          </button>

          {/* 图片计数 */}
          <div className="absolute top-4 left-1/2 -translate-x-1/2 z-10 bg-white/10 text-white px-4 py-2 rounded-full text-sm">
            {currentImageIndex + 1} / {selectedCase.images.length}
          </div>

          {/* 上一张按钮 */}
          {selectedCase.images.length > 1 && (
            <button 
              onClick={(e) => { e.stopPropagation(); prevImage(); }}
              className="absolute left-4 top-1/2 -translate-y-1/2 z-10 p-3 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors"
            >
              <ChevronLeft className="w-6 h-6" />
            </button>
          )}

          {/* 图片 */}
          <img 
            src={selectedCase.images[currentImageIndex]} 
            alt={selectedCase.title}
            className="max-w-[90vw] max-h-[85vh] object-contain"
            onClick={(e) => e.stopPropagation()}
          />

          {/* 下一张按钮 */}
          {selectedCase.images.length > 1 && (
            <button 
              onClick={(e) => { e.stopPropagation(); nextImage(); }}
              className="absolute right-4 top-1/2 -translate-y-1/2 z-10 p-3 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors"
            >
              <ChevronRight className="w-6 h-6" />
            </button>
          )}

          {/* 底部缩略图 */}
          {selectedCase.images.length > 1 && (
            <div 
              className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 max-w-[90vw] overflow-x-auto py-2"
              onClick={(e) => e.stopPropagation()}
            >
              {selectedCase.images.map((img, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentImageIndex(index)}
                  className={`w-16 h-12 rounded-lg overflow-hidden flex-shrink-0 border-2 transition-all ${
                    index === currentImageIndex 
                      ? 'border-white scale-110' 
                      : 'border-transparent opacity-60 hover:opacity-100'
                  }`}
                >
                  <img src={img} alt="" className="w-full h-full object-cover" />
                </button>
              ))}
            </div>
          )}

          {/* 案例信息 */}
          <div 
            className="absolute top-16 left-1/2 -translate-x-1/2 text-center"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="text-white text-lg font-semibold">{selectedCase.title}</h3>
            {selectedCase.description && (
              <p className="text-white/70 text-sm mt-1 max-w-lg">{selectedCase.description}</p>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
