import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/Components/ui/tabs";
import { Skeleton } from '@/Components/ui/skeleton';
import { Star, PenTool, Flame, Newspaper } from 'lucide-react';
import axios from 'axios';
import FeedItem from './FeedItem';
import useTranslation from '@/hooks/useTranslation';

const FeedSkeleton = () => (
    <div className="flex flex-row gap-3 sm:gap-6 items-stretch border-b border-border pb-6 pt-4 last:border-0 animate-in fade-in slide-in-from-bottom-2">
        <Skeleton className="shrink-0 w-[35%] sm:w-[240px] min-h-[100px] sm:min-h-[140px] rounded-[var(--radius)]" />
        <div className="flex-1 flex flex-col justify-between py-1">
            <div>
                <Skeleton className="h-3 w-16 mb-2 rounded-full" />
                <Skeleton className="h-5 sm:h-6 w-11/12 mb-2 rounded-[var(--radius)]" />
                <Skeleton className="h-5 sm:h-6 w-3/4 mb-2 rounded-[var(--radius)]" />
                <div className="hidden sm:block space-y-1.5 mt-2">
                    <Skeleton className="h-3 w-full" />
                    <Skeleton className="h-3 w-5/6" />
                </div>
            </div>
            <div className="flex flex-wrap items-center justify-between mt-2 w-full gap-2">
                <div className="flex items-center gap-2 sm:gap-4">
                    <div className="flex items-center gap-1.5">
                        <Skeleton className="h-4 w-4 sm:h-5 sm:w-5 rounded-full" />
                        <Skeleton className="h-3 w-16 sm:w-20 rounded-[var(--radius)]" />
                    </div>
                    <Skeleton className="h-3 w-px hidden sm:inline" />
                    <Skeleton className="h-3 w-16 rounded-[var(--radius)] hidden sm:flex" />
                </div>
                <div className="flex items-center gap-3">
                    <Skeleton className="h-6 w-20 rounded-full" />
                    <Skeleton className="h-4 w-8 rounded-[var(--radius)]" />
                </div>
            </div>
        </div>
    </div>
);

export default function HighlightedFeedTabs({ initialLatestData, auth, tabCounts }) {
    const { t } = useTranslation();
    const [activeTab, setActiveTab] = useState('latest');

    const activeTabsConfig = useMemo(() => {
        const allTabs = [
            { id: 'latest', label: t('_latest', 'Latest'), icon: Newspaper, show: true },
            { id: 'featured', label: t('_featured', 'Featured'), icon: Star, show: tabCounts?.featured > 0 },
            { id: 'editor_picks', label: t('_editors_pick', "Editor's Pick"), icon: PenTool, show: tabCounts?.editor_picks > 0 },
            { id: 'hot_news', label: t('_hot', 'Hot'), icon: Flame, show: tabCounts?.hot_news > 0 },
        ];
        return allTabs.filter(tab => tab.show);
    }, [tabCounts, t]);

    const [tabsState, setTabsState] = useState({
        latest: { items: [], page: 1, hasMore: true, loading: false, init: false, total: 0 },
        featured: { items: [], page: 1, hasMore: true, loading: false, init: false, total: 0 },
        editor_picks: { items: [], page: 1, hasMore: true, loading: false, init: false, total: 0 },
        hot_news: { items: [], page: 1, hasMore: true, loading: false, init: false, total: 0 },
    });

    useEffect(() => {
        if (initialLatestData && !tabsState.latest.init) {
            setTabsState(prev => ({
                ...prev,
                latest: {
                    items: Array.isArray(initialLatestData.data) ? initialLatestData.data : [],
                    page: initialLatestData.current_page || 1,
                    hasMore: initialLatestData.current_page < initialLatestData.last_page,
                    total: initialLatestData.total || 0,
                    loading: false,
                    init: true
                }
            }));
        }
    }, [initialLatestData]);

    const fetchTabPosts = async (tabKey, pageNum) => {
        setTabsState(prev => ({
            ...prev,
            [tabKey]: { ...prev[tabKey], loading: true }
        }));

        try {
            const res = await axios.get(`/api/latest-feed?tab=${tabKey}&page=${pageNum}`);
            const apiData = res.data;

            setTabsState(prev => {
                const existingItems = pageNum === 1 ? [] : prev[tabKey].items;
                const newItems = Array.isArray(apiData.data) ? apiData.data : [];
                
                return {
                    ...prev,
                    [tabKey]: {
                        items: [...existingItems, ...newItems],
                        page: apiData.current_page,
                        hasMore: apiData.current_page < apiData.last_page,
                        total: apiData.total,
                        loading: false,
                        init: true
                    }
                };
            });
        } catch (error) {
            console.error("Failed to fetch", error);
            setTabsState(prev => ({
                ...prev,
                [tabKey]: { ...prev[tabKey], loading: false, init: true }
            }));
        }
    };

    useEffect(() => {
        if (activeTab !== 'latest' && !tabsState[activeTab].init && !tabsState[activeTab].loading) {
            fetchTabPosts(activeTab, 1);
        }
    }, [activeTab]);

    const observer = useRef();
    const lastElementRef = useCallback((node) => {
        const currentTabState = tabsState[activeTab];
        if (currentTabState.loading) return;
        if (observer.current) observer.current.disconnect();
        
        observer.current = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting && currentTabState.hasMore) {
                fetchTabPosts(activeTab, currentTabState.page + 1);
            }
        }, { rootMargin: '150px' });
        
        if (node) observer.current.observe(node);
    }, [activeTab, tabsState]);

    useEffect(() => {
        if (!activeTabsConfig.find(t => t.id === activeTab)) {
            setActiveTab('latest');
        }
    }, [activeTabsConfig, activeTab]);

    return (
        <div>
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                
                {/* --- RESPONSIVE HORIZONTAL SCROLL WRAPPER --- */}
                <div className="w-full overflow-x-auto pb-2 mb-2 snap-x snap-mandatory [&::-webkit-scrollbar]:hidden [-ms-overflow-style:'none'] [scrollbar-width:'none']">
                    <TabsList className="h-auto p-1.5 flex flex-nowrap w-max min-w-full justify-start bg-muted/50 rounded-[var(--radius)]">
                        {activeTabsConfig.map(tab => (
                            <TabsTrigger 
                                key={tab.id} 
                                value={tab.id} 
                                className="gap-2 shrink-0 whitespace-nowrap px-4 py-2.5 data-[state=active]:text-primary rounded-[calc(var(--radius)-2px)] snap-start"
                            >
                                <tab.icon className="w-4 h-4 shrink-0" /> 
                                <span>{tab.label}</span>
                            </TabsTrigger>
                        ))}
                    </TabsList>
                </div>

                {activeTabsConfig.map(tab => {
                    const state = tabsState[tab.id];
                    const isFirstLoad = !state.init || (state.loading && state.items.length === 0);

                    return (
                        <TabsContent key={tab.id} value={tab.id}>
                            <div className="grid gap-0">
                                {isFirstLoad ? (
                                    <>
                                        {[1, 2, 3, 4, 5].map(i => (
                                            <FeedSkeleton key={`init-skel-${tab.id}-${i}`} />
                                        ))}
                                    </>
                                ) : state.items.length > 0 ? (
                                    <>
                                        {state.items.map((post, index) => {
                                            if (index === state.items.length - 1) {
                                                return (
                                                    <div ref={lastElementRef} key={`${tab.id}-${post.id}`}>
                                                        <FeedItem post={post} auth={auth} />
                                                    </div>
                                                );
                                            }
                                            return <FeedItem key={`${tab.id}-${post.id}`} post={post} auth={auth} />;
                                        })}
                                        
                                        {state.loading && (
                                            <div className="mt-2">
                                                <FeedSkeleton />
                                            </div>
                                        )}

                                        {!state.hasMore && (
                                            <div className="py-8 text-center text-xs text-muted-foreground italic uppercase tracking-widest">
                                                {t('_end_of_content', 'End of content')}
                                            </div>
                                        )}
                                    </>
                                ) : (
                                    <div className="text-center py-12 text-muted-foreground border border-dashed rounded-[var(--radius)] bg-muted/20">
                                        {t('_no_posts_found', 'No posts found.')}
                                    </div>
                                )}
                            </div>
                        </TabsContent>
                    );
                })}
            </Tabs>
        </div>
    );
}