import useAddOn from '@/hooks/use-addons';
import { CalendarClock, NotebookPen } from 'lucide-react';
import { useEffect, useState } from 'react';
import PinnedSection from './PinnedSection';
import NoteItem from './timeline/NoteItem';
import TimelineItem from './timeline/TimelineItem';
import { activityConfig } from './timeline/activityConfig';
import { createTimelineHandlers } from './timeline/timelineHandlers';
import type { TimelineGroup, TimelineProps } from './timeline/types';

export type { TimelineGroup, TimelineItem } from './timeline/types';

export default function Timeline({ groups, refetchData }: TimelineProps) {
    const [timelineData, setTimelineData] = useState<TimelineGroup[]>(groups);
    const { addOnOpen, addOnClose } = useAddOn();

    // Sync internal state with prop changes
    useEffect(() => {
        setTimelineData(groups);
    }, [groups]);

    // Create timeline handlers
    const { onTaskDelete, handleEditByType, handleViewByType, onTaskPin } = createTimelineHandlers({
        timelineData,
        setTimelineData,
        addOnOpen,
        addOnClose,
        refetchData,
    });

    // Extract all pinned items from all groups
    const pinnedItems = timelineData.flatMap((group) => group.items.filter((item) => item.isPinned));

    // Filter out pinned items from regular groups
    const regularGroups = timelineData
        .map((group) => ({
            ...group,
            items: group.items.filter((item) => !item.isPinned),
        }))
        .filter((group) => group.items.length > 0);

    if (!groups || groups.length === 0) {
        return (
            <div className="flex flex-col items-center justify-center py-12 text-center">
                <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-slate-100">
                    <CalendarClock className="h-8 w-8 text-slate-400" />
                </div>
                <p className="text-sm font-medium text-slate-600">No data found!</p>
                <p className="mt-1 text-xs text-slate-500">Activity will appear here as it happens</p>
            </div>
        );
    }

    return (
        <div className="w-full">
            {/* Pinned Section */}
            <PinnedSection
                pinnedItems={pinnedItems}
                onTaskPin={onTaskPin}
                onTaskDelete={onTaskDelete}
                onTaskEdit={handleEditByType}
                onTaskView={handleViewByType}
                getActivityConfig={(type: string) => activityConfig[type as keyof typeof activityConfig] || activityConfig.default}
            />

            {/* Regular Timeline Groups */}
            {regularGroups.map((group) => (
                <div key={group.label} className="relative pb-1 last:pb-0">
                    {/* Date Header - Clean & Minimal */}
                    <div className="sticky top-0 z-10 mx-2 my-4 bg-white/95 backdrop-blur-sm">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <CalendarClock className="h-4 w-4 text-slate-400" />
                                <span className="text-sm font-bold tracking-wider text-slate-700 uppercase">{group.label}</span>
                            </div>
                            <span className="rounded-md bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-500">{group.items.length}</span>
                        </div>
                    </div>

                    {/* Separate notes from other items */}
                    {(() => {
                        const notes = group.items.filter((item) => item.type === 'note');
                        const otherItems = group.items.filter((item) => item.type !== 'note');

                        return (
                            <>
                                {/* Notes Grid - 3 columns with timeline */}
                                {notes.length > 0 && (
                                    <div className="relative mb-8">
                                        {/* Vertical Timeline Line for Notes */}
                                        <div className="absolute top-0 bottom-0 left-4 w-px bg-gradient-to-b from-slate-200 via-slate-300 to-slate-200" />

                                        <div className="relative pl-12">
                                            {/* Timeline Dot for Notes Section */}
                                            <TimelineDot icon={<NotebookPen className="h-4 w-4 text-white" />} color="bg-yellow-500" />

                                            <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
                                                {notes.map((item, index) => (
                                                    <NoteItem
                                                        key={item.id}
                                                        item={item}
                                                        index={index}
                                                        onPin={onTaskPin}
                                                        onDelete={onTaskDelete}
                                                        onEdit={handleEditByType}
                                                        onView={handleViewByType}
                                                    />
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* TODO Timeline Container for other items */}
                                {otherItems.length > 0 && (
                                    <div className="relative">
                                        {/* Vertical Timeline Line - Enhanced */}
                                        <div className="absolute top-0 bottom-0 left-4 w-px bg-slate-200" />
                                        {/* Activity Items */}
                                        <div className="space-y-6">
                                            {otherItems.map((item, index) => (
                                                <TimelineItem
                                                    key={item.id}
                                                    item={item}
                                                    index={index}
                                                    onPin={onTaskPin}
                                                    onDelete={onTaskDelete}
                                                    onEdit={handleEditByType}
                                                    onView={handleViewByType}
                                                />
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </>
                        );
                    })()}
                </div>
            ))}

            {/* Animation styles */}
            <style>{`
                @keyframes fadeInUp {
                    from {
                        opacity: 0;
                        transform: translateY(20px);
                    }
                    to {
                        opacity: 1;
                        transform: translateY(0);
                    }
                }
            `}</style>
        </div>
    );
}

interface TimelineDotProps {
    icon: React.ReactNode;
    color: string;
}
/**
 * Reusable TimelineDot component
 */
function TimelineDot({ icon, color }: TimelineDotProps) {
    return (
        <div className="absolute top-1 left-0 flex items-center justify-center">
            <div className={`absolute h-8 w-8 ${color} rounded-full opacity-0 transition-all duration-300 hover:scale-125 hover:opacity-10`} />
            <div
                className={`relative z-10 flex h-8 w-8 items-center justify-center rounded-full ${color} shadow-lg ring-4 ring-white transition-transform duration-200`}
            >
                {icon}
            </div>
        </div>
    );
}
