import React, { useState, useEffect } from "react";
import { Megaphone } from "lucide-react";
import { Link } from "@inertiajs/react";
import { Post } from "@/components/DetailArtikel/types";

interface RunningTextProps {
    posts: Post[];
}

export default function RunningText({ posts }: RunningTextProps) {
    const [currentMessageIndex, setCurrentMessageIndex] = useState(0);
    const [isVisible, setIsVisible] = useState(true);
    const [isPaused, setIsPaused] = useState(false);

    const getLatestPostsByCategory = () => {
        const groupedPosts = posts.reduce((acc, post) => {
            const category = post.kategori?.NamaKategori || "Uncategorized";
            if (!acc[category]) {
                acc[category] = [];
            }
            acc[category].push(post);
            return acc;
        }, {} as Record<string, Post[]>);

        // Get latest 2 posts from each category and flatten
        return Object.values(groupedPosts)
            .map((categoryPosts) =>
                categoryPosts
                    .sort(
                        (a, b) =>
                            new Date(b.created_at).getTime() -
                            new Date(a.created_at).getTime()
                    )
                    .slice(0, 2)
            )
            .flat();
    };

    const messages = getLatestPostsByCategory();

    useEffect(() => {
        if (isPaused || messages.length === 0) return;

        const interval = setInterval(() => {
            setIsVisible(false);

            setTimeout(() => {
                setCurrentMessageIndex(
                    (prevIndex) => (prevIndex + 1) % messages.length
                );
                setIsVisible(true);
            }, 500);
        }, 3000);

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

    const getRouteByCategory = (kategori: string, slug: string) => {
        const routes: { [key: string]: string } = {
            Pengumuman: `/pengumuman/${slug}`,
            Peraturan: `/peraturan/${slug}`,
            Undangan: `/undangan/${slug}`,
        };

        return routes[kategori] || `/sekilasinfo/${slug}`;
    };

    if (messages.length === 0) return null;

    return (
        <div
            className="w-full bg-green-100 p-2 flex overflow-hidden"
            onMouseEnter={() => setIsPaused(true)}
            onMouseLeave={() => setIsPaused(false)}
        >
            <div className="flex container max-w-7xl px-8 relative">
                <Megaphone className="w-5 h-5 mr-2 text-black flex-shrink-0" />
                <div className="overflow-hidden relative h-[1.5rem]">
                    <Link
                        href={getRouteByCategory(
                            messages[currentMessageIndex].kategori
                                ?.NamaKategori || "",
                            messages[currentMessageIndex].SlugPost
                        )}
                        className="hover:text-green-700 transition-colors"
                    >
                        <p
                            className={`text-sm text-black transition-opacity duration-500 ease-in-out ${
                                isVisible ? "opacity-100" : "opacity-0"
                            }`}
                        >
                            <span className="font-semibold mr-2 bg-green-600 p-1 text-white text-xs  rounded">
                                {
                                    messages[currentMessageIndex].kategori
                                        ?.NamaKategori
                                }
                            </span>
                            <span>
                                {" "}
                                {messages[currentMessageIndex].JudulPost}
                            </span>
                        </p>
                    </Link>
                </div>
            </div>
        </div>
    );
}
