'use client';

import * as React from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Badge } from '@/components/ui/badge';

interface Article {
  slug: string;
  title: string;
  excerpt: string | null;
  cardImage: string | null;
  publicationDate: Date | null;
  category: string | null;
  readingTime: number | null;
}

interface LatestArticlesProps {
  articles: Article[];
}

/**
 * LatestArticles Component - Redesigned to match website theme
 * 
 * Displays the latest articles in a horizontal scrollable carousel.
 * 
 * Features:
 * - Section header with vertical red accent bar
 * - Dark theme background (#0F0F12)
 * - Cards with red hover effects and glow
 * - Red numbered badges
 * - Styled navigation buttons
 * - Smooth scroll behavior
 * - Responsive design
 */
export function LatestArticles({ articles }: LatestArticlesProps) {
  const scrollContainerRef = React.useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = React.useState(false);
  const [canScrollRight, setCanScrollRight] = React.useState(true);

  // Limit to 10 articles
  const displayArticles = articles.slice(0, 10);

  // Check scroll position to show/hide navigation buttons
  const checkScrollPosition = React.useCallback(() => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const { scrollLeft, scrollWidth, clientWidth } = container;
    setCanScrollLeft(scrollLeft > 0);
    setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10);
  }, []);

  // Scroll left (scroll by 4 cards)
  const scrollLeft = () => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const cardWidth = container.querySelector('.latest-article-card')?.clientWidth || 250;
    const scrollAmount = (cardWidth + 16) * 4; // 4 cards + gaps
    container.scrollBy({
      left: -scrollAmount,
      behavior: 'smooth',
    });
  };

  // Scroll right (scroll by 4 cards)
  const scrollRight = () => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const cardWidth = container.querySelector('.latest-article-card')?.clientWidth || 250;
    const scrollAmount = (cardWidth + 16) * 4; // 4 cards + gaps
    container.scrollBy({
      left: scrollAmount,
      behavior: 'smooth',
    });
  };

  // Set up scroll listener
  React.useEffect(() => {
    const container = scrollContainerRef.current;
    if (!container) return;

    checkScrollPosition();
    container.addEventListener('scroll', checkScrollPosition);
    window.addEventListener('resize', checkScrollPosition);

    return () => {
      container.removeEventListener('scroll', checkScrollPosition);
      window.removeEventListener('resize', checkScrollPosition);
    };
  }, [checkScrollPosition]);

  if (displayArticles.length === 0) {
    return (
      <section className="py-12 md:py-16 bg-[#0F0F12]">
        <div className="container">
          {/* Section header with red accent bar */}
          <div className="flex items-center gap-3 mb-8">
            <div className="w-1 h-8 bg-[#E60023] rounded-full" />
            <h2 className="text-3xl md:text-4xl font-bold text-white">
              最新記事
            </h2>
          </div>
          <div className="text-center py-12">
            <p className="text-[#B8B8C0] text-lg">
              記事がまだありません
            </p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="py-12 md:py-16 bg-[#0F0F12]">
      <div className="container">
        {/* Section header with red accent bar and navigation buttons */}
        <div className="flex items-center justify-between mb-8">
          {/* Section heading with vertical red accent bar */}
          <div className="flex items-center gap-3">
            <div className="w-1 h-8 bg-[#E60023] rounded-full" />
            <h2 className="text-3xl md:text-4xl font-bold text-white">
              最新記事
            </h2>
          </div>
          
          {/* Navigation buttons */}
          <div className="flex gap-2">
            <button
              onClick={scrollLeft}
              disabled={!canScrollLeft}
              className="w-10 h-10 rounded-full bg-[#202026] hover:bg-[#E60023] disabled:bg-[#202026] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center text-white transition-all duration-200 hover:shadow-[0_0_15px_rgba(230,0,35,0.4)]"
              aria-label="前の記事"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>
            <button
              onClick={scrollRight}
              disabled={!canScrollRight}
              className="w-10 h-10 rounded-full bg-[#202026] hover:bg-[#E60023] disabled:bg-[#202026] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center text-white transition-all duration-200 hover:shadow-[0_0_15px_rgba(230,0,35,0.4)]"
              aria-label="次の記事"
            >
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>
        </div>
        
        {/* Scrollable container */}
        <div
          ref={scrollContainerRef}
          className="flex gap-6 overflow-x-auto scroll-smooth scrollbar-hide"
          style={{
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
          }}
        >
          {displayArticles.map((article, index) => {
            const displayNumber = index + 1;
            
            return (
              <Link
                key={article.slug}
                href={`/post/${article.slug}`}
                className="latest-article-card flex-shrink-0 w-[280px] sm:w-[calc(50%-12px)] lg:w-[calc(25%-18px)] group"
              >
                {/* Card with dark theme and red hover effects */}
                <div className="bg-[#202026] rounded-xl overflow-hidden border border-[#2A2A33] transition-all duration-200 hover:border-[#E60023] hover:shadow-[0_0_20px_rgba(230,0,35,0.3)] h-full flex flex-col">
                  {/* Article Image */}
                  <div className="relative h-[180px] overflow-hidden">
                    {article.cardImage ? (
                      <Image
                        src={article.cardImage}
                        alt={article.title}
                        fill
                        className="object-cover group-hover:scale-105 transition-transform duration-300"
                        sizes="(max-width: 640px) 280px, (max-width: 1024px) 50vw, 25vw"
                        priority={index < 4}
                      />
                    ) : (
                      <div className="w-full h-full bg-gradient-to-br from-[#1A1A1F] to-[#202026]" />
                    )}
                    
                    {/* Red numbered badge */}
                    <div className="absolute top-3 left-3 bg-[#E60023] text-white font-bold text-xl w-10 h-10 rounded-lg flex items-center justify-center shadow-lg">
                      {displayNumber}
                    </div>
                  </div>
                  
                  {/* Card content */}
                  <div className="p-4 flex-1 flex flex-col">
                    {/* Category badge */}
                    {article.category && (
                      <Badge className="w-fit mb-3 bg-[#E60023] text-white hover:bg-[#FF2A3D] text-xs">
                        {article.category}
                      </Badge>
                    )}
                    
                    {/* Title */}
                    <h3 className="text-white font-bold text-base leading-tight line-clamp-2 group-hover:text-[#E60023] transition-colors mb-3">
                      {article.title}
                    </h3>
                    
                    {/* Metadata */}
                    <div className="mt-auto flex items-center gap-3 text-sm text-[#B8B8C0]">
                      {article.publicationDate && (
                        <time>
                          {new Date(article.publicationDate).toLocaleDateString('ja-JP', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                          })}
                        </time>
                      )}
                      {article.readingTime && (
                        <>
                          <span>•</span>
                          <span>{article.readingTime}分</span>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              </Link>
            );
          })}
        </div>
      </div>

      {/* Hide scrollbar CSS */}
      <style jsx>{`
        .scrollbar-hide::-webkit-scrollbar {
          display: none;
        }
      `}</style>
    </section>
  );
}
