'use client';

import { Calendar, Newspaper, Trophy, Mic2, FileText, TrendingUp, ChevronLeft, ChevronRight } from 'lucide-react';
import { format } from 'date-fns';
import { id as localeId } from 'date-fns/locale';
import { useRef, useEffect, useState } from 'react';

interface MediaFeedItem {
    id: string;
    judul: string;
    narasi: string | null;
    imageUrl: string | null;
    createdAt: Date | string;
    type: 'berita' | 'prestasi' | 'rangers-talk' | 'laporan-keuangan';
    tipeDisplay: string;
    tabel?: string | null;
    periode?: string;
}

export default function KabarFeedSection({ items }: { items: MediaFeedItem[] }) {
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const [isHovered, setIsHovered] = useState(false);

    // Auto scroll logic
    useEffect(() => {
        if (!scrollContainerRef.current || isHovered || items.length === 0) return;
        
        const interval = setInterval(() => {
            if (scrollContainerRef.current) {
                const { scrollLeft, scrollWidth, clientWidth } = scrollContainerRef.current;
                // If reached end, scroll back to start seamlessly or instantly
                if (scrollLeft + clientWidth >= scrollWidth - 10) {
                    scrollContainerRef.current.scrollTo({ left: 0, behavior: 'smooth' });
                } else {
                    // Scroll right by a specific amount (approx 1 card width + gap)
                    scrollContainerRef.current.scrollBy({ left: 280, behavior: 'smooth' });
                }
            }
        }, 3500); // 3.5 seconds

        return () => clearInterval(interval);
    }, [isHovered, items.length]);

    const scroll = (direction: 'left' | 'right') => {
        if (scrollContainerRef.current) {
            const amount = 280;
            scrollContainerRef.current.scrollBy({ left: direction === 'left' ? -amount : amount, behavior: 'smooth' });
        }
    };

    const getIcon = (type: string) => {
        switch (type) {
            case 'berita': return <Newspaper className="w-3.5 h-3.5" />;
            case 'prestasi': return <Trophy className="w-3.5 h-3.5 text-amber-400" />;
            case 'rangers-talk': return <Mic2 className="w-3.5 h-3.5 text-red-400" />;
            case 'laporan-keuangan': return <FileText className="w-3.5 h-3.5 text-emerald-400" />;
            default: return <Newspaper className="w-3.5 h-3.5" />;
        }
    };

    const getLinkPath = (item: MediaFeedItem) => {
        switch (item.type) {
            case 'berita': return `/berita/${item.id}`;
            case 'prestasi': return `/prestasi/${item.id}`;
            case 'rangers-talk': return `/rangers-talk/${item.id}`;
            case 'laporan-keuangan': return `/laporan-keuangan/${item.id}`;
            default: return `/berita/${item.id}`;
        }
    };

    const [isDragging, setIsDragging] = useState(false);
    const [startX, setStartX] = useState(0);
    const [scrollLeftState, setScrollLeftState] = useState(0);

    const onMouseDown = (e: React.MouseEvent) => {
        setIsDragging(true);
        if (scrollContainerRef.current) {
            setStartX(e.pageX - scrollContainerRef.current.offsetLeft);
            setScrollLeftState(scrollContainerRef.current.scrollLeft);
        }
    };

    const onMouseLeave = () => {
        setIsDragging(false);
        setIsHovered(false);
    };

    const onMouseUp = () => {
        setIsDragging(false);
    };

    const onMouseMove = (e: React.MouseEvent) => {
        if (!isDragging || !scrollContainerRef.current) return;
        e.preventDefault();
        const x = e.pageX - scrollContainerRef.current.offsetLeft;
        const walk = (x - startX) * 2; // Scroll-fast multiplier
        scrollContainerRef.current.scrollLeft = scrollLeftState - walk;
    };

    return (
        <section data-theme="dark" className="w-full py-12 md:py-16 bg-[#07090f] relative overflow-hidden">
            {/* Background Effects (Dark Glassmorphism style) */}
            <div className="absolute top-0 left-0 w-full h-full pointer-events-none z-0">
                <div className="absolute inset-0 opacity-[0.03]" style={{backgroundImage: 'radial-gradient(#ffffff 2px, transparent 2px)', backgroundSize: '40px 40px'}}></div>
                <div className="absolute top-1/4 left-1/4 w-[40rem] h-[40rem] bg-blue-600/10 rounded-full blur-[120px]"></div>
                <div className="absolute bottom-1/4 right-1/4 w-[40rem] h-[40rem] bg-indigo-600/10 rounded-full blur-[120px]"></div>
            </div>
            
            <div className="container px-6 md:px-12 max-w-[1100px] mx-auto relative z-10">
                
                {/* Header Section */}
                <div className="flex flex-col md:flex-row justify-between items-end mb-6">
                    <div className="space-y-2">
                        <h2 className="text-2xl md:text-3xl lg:text-4xl font-extrabold text-white tracking-tighter">
                            Informasi Terkini
                        </h2>
                    </div>
                    
                    {/* Navigation Arrows */}
                    <div className="hidden md:flex items-center gap-2 mt-4 md:mt-0">
                        <button onClick={() => scroll('left')} className="p-3 rounded-full bg-white/10 text-white hover:bg-white/20 border border-white/10 backdrop-blur-md transition-all">
                            <ChevronLeft className="w-5 h-5" />
                        </button>
                        <button onClick={() => scroll('right')} className="p-3 rounded-full bg-white/10 text-white hover:bg-white/20 border border-white/10 backdrop-blur-md transition-all">
                            <ChevronRight className="w-5 h-5" />
                        </button>
                    </div>
                </div>

                {/* Carousel Container */}
                <div 
                    className="relative w-full -mx-6 px-6 md:mx-0 md:px-0"
                    onMouseEnter={() => setIsHovered(true)}
                    onMouseLeave={onMouseLeave}
                >
                    <div 
                        ref={scrollContainerRef}
                        className={`flex overflow-x-auto snap-x snap-mandatory hide-scrollbar gap-4 pb-6 ${isDragging ? 'cursor-grabbing' : 'cursor-grab'}`}
                        style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
                        onMouseDown={onMouseDown}
                        onMouseUp={onMouseUp}
                        onMouseMove={onMouseMove}
                    >
                        {items.length === 0 ? (
                            <div className="w-full flex items-center justify-center min-h-[250px] border border-white/10 rounded-[1.25rem] bg-white/5 backdrop-blur-md">
                                <p className="text-white/50 font-medium text-sm">Belum ada kabar media terbaru.</p>
                            </div>
                        ) : (
                            items.map((item) => (
                                <a 
                                    key={item.id} 
                                    href={getLinkPath(item)}
                                    onDragStart={(e) => e.preventDefault()}
                                    onClick={(e) => {
                                        if (scrollContainerRef.current && Math.abs(scrollContainerRef.current.scrollLeft - scrollLeftState) > 5) {
                                            e.preventDefault();
                                        }
                                    }}
                                    className="snap-start shrink-0 w-[200px] md:w-[220px] xl:w-[240px] aspect-[4/5] relative group rounded-[1.25rem] overflow-hidden cursor-pointer shadow-lg border border-white/10 bg-white/5 backdrop-blur-md block"
                                >
                                    {/* Image with 4:5 aspect ratio (IG feed style) */}
                                    {item.imageUrl ? (
                                        // eslint-disable-next-line @next/next/no-img-element
                                        <img 
                                            src={item.imageUrl} 
                                            alt={item.judul} 
                                            className="absolute inset-0 w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" 
                                        />
                                    ) : (
                                        <div className="absolute inset-0 flex flex-col items-center justify-center text-white/30 bg-[#0B1F3A]/50">
                                            {getIcon(item.type)}
                                        </div>
                                    )}

                                    {/* Gradient Overlay for Text Visibility */}
                                    <div className="absolute inset-0 bg-gradient-to-t from-[#07090f] via-[#07090f]/60 to-transparent opacity-80 group-hover:opacity-90 transition-opacity duration-300"></div>
                                    
                                    {/* Content Overlay */}
                                    <div className="absolute inset-0 p-4 flex flex-col justify-end transform translate-y-3 group-hover:translate-y-0 transition-transform duration-300">
                                        <div className="flex items-center gap-2 mb-2">
                                            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-white/20 backdrop-blur-md text-white text-[8px] font-bold uppercase tracking-wider border border-white/10 shadow-sm">
                                                {getIcon(item.type)} {item.tipeDisplay}
                                            </span>
                                        </div>
                                        
                                        <h4 className="font-extrabold text-base md:text-lg text-white leading-tight line-clamp-3 group-hover:text-blue-400 transition-colors mb-1.5">
                                            {item.judul}
                                        </h4>
                                        
                                        <div className="flex items-center gap-1.5 text-white/70 text-[10px] font-medium">
                                            <Calendar className="w-3 h-3" />
                                            {format(new Date(item.createdAt), 'dd MMM yyyy', { locale: localeId })}
                                        </div>
                                    </div>
                                </a>
                            ))
                        )}
                    </div>
                </div>
            </div>
            
            {/* Custom style for hide-scrollbar */}
            <style jsx>{`
                .hide-scrollbar::-webkit-scrollbar {
                    display: none;
                }
            `}</style>
        </section>
    );
}
