import useAddOn from '@/hooks/use-addons';
import { Building, CalendarClock, ClipboardList, Edit, Eye, Mail, MoreHorizontal, NotebookPen, Phone, Pin, Trash2, Video } from 'lucide-react';
import { useEffect, useState } from 'react';
import NoteCard from './NoteCard';
import PinnedSection from './PinnedSection';
import { createTimelineHandlers } from './timeline/timelineHandlers';
import { TimelineGroup, TimelineItem, TimelineProps } from './timeline/types';
import { Button } from './ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './ui/dropdown-menu';

// Re-export types for backward compatibility
export type { TimelineGroup, TimelineItem };

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

    // Log the incoming groups data
    useEffect(() => {
        const totalItems = groups.flatMap((group) => group.items).length;
        const pinnedItems = groups.flatMap((group) => group.items).filter((item) => item.isPinned).length;
        console.log('🔄 Timeline received groups:', {
            groups,
            totalItems,
            pinnedItems,
            pinnedItemsDetails: groups
                .flatMap((group) => group.items)
                .filter((item) => item.isPinned)
                .map((item) => ({ id: item.id, title: item.title, type: item.type })),
        });
    }, [groups]);

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

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

    const getActivityConfig = (type: string) => {
        return activityConfig[type as keyof typeof activityConfig] || activityConfig.default;
    };

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

    // Log pinned items extraction
    useEffect(() => {
        console.log('📌 Extracted pinned items:', {
            count: pinnedItems.length,
            items: pinnedItems.map((item) => ({ id: item.id, title: item.title, type: item.type })),
        });
    }, [pinnedItems]);

    // 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 activity yet</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={getActivityConfig}
            />

            {/* Regular Timeline Groups */}
            {regularGroups.map((group, groupIndex) => (
                <div key={groupIndex} 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 */}
                                            <div className="absolute top-1 left-0 flex items-center justify-center">
                                                <div
                                                    className={`absolute h-8 w-8 rounded-full bg-yellow-500 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 bg-yellow-500 shadow-lg ring-4 ring-white transition-transform duration-200`}
                                                >
                                                    <NotebookPen className="h-4 w-4 text-white" />
                                                </div>
                                            </div>

                                            <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
                                                {notes.map((item, itemIndex) => {
                                                    const config = getActivityConfig(item.type);

                                                    return (
                                                        <div
                                                            key={`note-${itemIndex}`}
                                                            style={{
                                                                animation: `fadeInUp 0.4s ease-out ${itemIndex * 0.05}s both`,
                                                            }}
                                                        >
                                                            <NoteCard
                                                                id={item.id}
                                                                title={item.title}
                                                                content={item.description || ''}
                                                                createdAt={item.timestamp}
                                                                tag={config.label}
                                                                tagColor="border-yellow-200 bg-yellow-50 text-yellow-800"
                                                                borderTopColor={config.borderColor}
                                                                isPinned={item.isPinned}
                                                                onTogglePin={() => onTaskPin(item.id)}
                                                                onDelete={() => onTaskDelete(item.id)}
                                                                onEdit={() => handleEditByType(item.id, item.type)}
                                                                onView={() => handleViewByType(item.id, item.type)}
                                                                creator={
                                                                    item.metadata?.[0]
                                                                        ? {
                                                                              name: String(item.metadata[0].value),
                                                                              avatar: undefined,
                                                                          }
                                                                        : undefined
                                                                }
                                                            />
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* 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-gradient-to-b from-slate-200 via-slate-300 to-slate-200" />

                                        {/* Activity Items */}
                                        <div className="space-y-6">
                                            {otherItems.map((item, itemIndex) => {
                                                const config = getActivityConfig(item.type);
                                                const IconComponent = config.icon;
                                                const isFirst = itemIndex === 0;
                                                const isLast = itemIndex === otherItems.length - 1;

                                                return (
                                                    <div
                                                        key={itemIndex}
                                                        className="group/item relative pl-12"
                                                        style={{
                                                            animation: `fadeInUp 0.4s ease-out ${itemIndex * 0.05}s both`,
                                                        }}
                                                    >
                                                        {/* Timeline Dot - Enhanced with pulse */}
                                                        <div className="absolute top-1 left-0 flex items-center justify-center">
                                                            {/* Pulse effect on hover */}
                                                            <div
                                                                className={`absolute h-8 w-8 ${config.iconBg} rounded-full opacity-0 transition-all duration-300 group-hover/item:scale-125 group-hover/item:opacity-10`}
                                                            />

                                                            <div
                                                                className={`relative h-8 w-8 ${config.iconBg} z-10 flex items-center justify-center rounded-full shadow-lg ring-4 ring-white transition-transform duration-200 group-hover/item:scale-105`}
                                                            >
                                                                <IconComponent className="h-4 w-4 text-white" />
                                                            </div>
                                                        </div>

                                                        {/* Card - Premium Design */}
                                                        <div
                                                            className={`relative border border-slate-200/80 bg-white ${config.borderColor} cursor-pointer overflow-hidden rounded-xl border-t-2 transition-all duration-200 hover:border-slate-300/80 hover:shadow-sm`}
                                                        >
                                                            {/* Subtle gradient overlay */}
                                                            <div className="pointer-events-none absolute inset-0 bg-gradient-to-br from-white via-transparent to-slate-50/30" />

                                                            <div className="relative p-4">
                                                                {/* Header with better spacing */}
                                                                <div className="mb-2 flex items-start justify-between gap-3">
                                                                    <div className="flex min-w-0 flex-1 items-center gap-2.5">
                                                                        <span
                                                                            className={`inline-flex items-center gap-1 text-[11px] font-extrabold ${config.accentColor} rounded-md border border-slate-100 bg-slate-50 px-2.5 py-1 tracking-widest uppercase`}
                                                                        >
                                                                            {config.label}
                                                                        </span>
                                                                    </div>
                                                                    <DropdownMenu>
                                                                        <DropdownMenuTrigger asChild>
                                                                            <Button variant="ghost" size="sm" className="h-6 w-6 p-0">
                                                                                <MoreHorizontal className="h-4 w-4 text-gray-400" />
                                                                            </Button>
                                                                        </DropdownMenuTrigger>
                                                                        <DropdownMenuContent align="end">
                                                                            <DropdownMenuItem onClick={() => handleViewByType(item.id, item.type)}>
                                                                                <Eye className="mr-2 h-3 w-3" />
                                                                                View
                                                                            </DropdownMenuItem>
                                                                            <DropdownMenuItem onClick={() => handleEditByType(item.id, item.type)}>
                                                                                <Edit className="mr-2 h-3 w-3" />
                                                                                Edit
                                                                            </DropdownMenuItem>

                                                                            <DropdownMenuItem onClick={() => onTaskPin(item.id)}>
                                                                                <Pin className="mr-2 h-3 w-3" />
                                                                                {item.isPinned ? 'Unpin' : 'Pin'}
                                                                            </DropdownMenuItem>

                                                                            <DropdownMenuItem
                                                                                className="text-red-600"
                                                                                onClick={() => onTaskDelete(item.id)}
                                                                            >
                                                                                <Trash2 className="mr-2 h-3 w-3" />
                                                                                Delete
                                                                            </DropdownMenuItem>
                                                                        </DropdownMenuContent>
                                                                    </DropdownMenu>
                                                                </div>

                                                                {/* Title - Better typography */}
                                                                <h4 className="mb-2 line-clamp-2 text-[15px] leading-snug font-semibold text-slate-900 transition-colors">
                                                                    {item.title}
                                                                </h4>

                                                                {/* Description - Improved readability */}
                                                                {item.description && (
                                                                    <p className="mb-2 line-clamp-3 text-[13px] leading-relaxed text-slate-600">
                                                                        {item.description}
                                                                    </p>
                                                                )}

                                                                {/* Metadata Pills - Enhanced design */}
                                                                {item.metadata && item.metadata.length > 0 && (
                                                                    <div className="mb-2 flex flex-wrap gap-2">
                                                                        {item.metadata.map((meta, metaIndex) => (
                                                                            <div
                                                                                key={metaIndex}
                                                                                className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200/60 bg-gradient-to-br from-slate-50 to-slate-100/50 px-3 py-1.5 text-[11px] shadow-sm"
                                                                            >
                                                                                <span className="text-slate-400">{meta.icon}</span>
                                                                                <span className="font-bold text-slate-600">{meta.label}:</span>
                                                                                <span className="max-w-[200px] truncate font-bold text-slate-900">
                                                                                    {typeof meta.value === 'object' && meta.value !== null
                                                                                        ? JSON.stringify(meta.value)
                                                                                        : meta.value}
                                                                                </span>
                                                                            </div>
                                                                        ))}
                                                                        <div className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200/60 bg-gradient-to-br from-slate-50 to-slate-100/50 px-3 py-1.5 text-[11px] shadow-sm">
                                                                            <span className="font-bold text-slate-600">Assigned by:</span>
                                                                            <span className="max-w-[200px] truncate font-bold text-slate-900">
                                                                                John
                                                                            </span>
                                                                        </div>
                                                                    </div>
                                                                )}

                                                                {/* Status Content - Better separation */}
                                                                {item.content && (
                                                                    <div className="mt-3 border-t border-slate-200/60 pt-4">{item.content}</div>
                                                                )}

                                                                <div className="flex items-end justify-between gap-3">
                                                                    {/* Status Badges with Icons */}
                                                                    <div className="mt-3 flex flex-wrap gap-2">
                                                                        {item.type === 'task' && (
                                                                            <>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1 text-[10px] font-semibold text-blue-700">
                                                                                    <ClipboardList className="h-3 w-3" />
                                                                                    In Progress
                                                                                </span>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-purple-200 bg-purple-50 px-2.5 py-1 text-[10px] font-semibold text-purple-700">
                                                                                    <CalendarClock className="h-3 w-3" />
                                                                                    High Priority
                                                                                </span>
                                                                            </>
                                                                        )}
                                                                        {item.type === 'email' && (
                                                                            <>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-1 text-[10px] font-semibold text-emerald-700">
                                                                                    <Mail className="h-3 w-3" />
                                                                                    Sent
                                                                                </span>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-2.5 py-1 text-[10px] font-semibold text-amber-700">
                                                                                    <Building className="h-3 w-3" />
                                                                                    Business
                                                                                </span>
                                                                            </>
                                                                        )}
                                                                        {item.type === 'call' && (
                                                                            <>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-cyan-200 bg-cyan-50 px-2.5 py-1 text-[10px] font-semibold text-cyan-700">
                                                                                    <Phone className="h-3 w-3" />
                                                                                    Completed
                                                                                </span>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[10px] font-semibold text-slate-700">
                                                                                    <CalendarClock className="h-3 w-3" />
                                                                                    45 min
                                                                                </span>
                                                                            </>
                                                                        )}
                                                                        {item.type === 'meeting' && (
                                                                            <>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-purple-200 bg-purple-50 px-2.5 py-1 text-[10px] font-semibold text-purple-700">
                                                                                    <Video className="h-3 w-3" />
                                                                                    Scheduled
                                                                                </span>
                                                                                <span className="inline-flex items-center gap-1 rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-1 text-[10px] font-semibold text-indigo-700">
                                                                                    <Building className="h-3 w-3" />
                                                                                    Conference Room A
                                                                                </span>
                                                                            </>
                                                                        )}
                                                                        {item.type === 'reminder' && (
                                                                            <span className="inline-flex items-center gap-1 rounded-full border border-orange-200 bg-orange-50 px-2.5 py-1 text-[10px] font-semibold text-orange-700">
                                                                                <CalendarClock className="h-3 w-3" />
                                                                                Upcoming
                                                                            </span>
                                                                        )}
                                                                    </div>
                                                                    <time
                                                                        className="rounded bg-slate-50 px-2 py-0.5 text-[11px] font-semibold whitespace-nowrap text-slate-500"
                                                                        dateTime={item.timestamp}
                                                                    >
                                                                        {item.date}
                                                                    </time>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>
                                )}
                            </>
                        );
                    })()}
                </div>
            ))}

            {/* Add subtle animation keyframes via inline style */}
            <style>{`
                @keyframes fadeInUp {
                    from {
                        opacity: 0;
                        transform: translateY(20px);
                    }
                    to {
                        opacity: 1;
                        transform: translateY(0);
                    }
                }
            `}</style>
        </div>
    );
}

// Activity type configuration - Clean, minimal design with distinct colors
export const activityConfig = {
    task: {
        icon: ClipboardList,
        label: 'Task',
        iconBg: 'bg-blue-500',
        iconColor: 'text-white',
        accentColor: 'text-blue-600',
        borderColor: 'border-t-blue-500',
    },
    note: {
        icon: NotebookPen,
        label: 'Note',
        iconBg: 'bg-yellow-500',
        iconColor: 'text-white',
        accentColor: 'text-yellow-600',
        borderColor: 'border-t-yellow-500',
    },
    reminder: {
        icon: CalendarClock,
        label: 'Reminder',
        iconBg: 'bg-orange-500',
        iconColor: 'text-white',
        accentColor: 'text-orange-600',
        borderColor: 'border-t-orange-500',
    },
    email: {
        icon: Mail,
        label: 'Email',
        iconBg: 'bg-emerald-500',
        iconColor: 'text-white',
        accentColor: 'text-emerald-600',
        borderColor: 'border-t-emerald-500',
    },
    call: {
        icon: Phone,
        label: 'Call',
        iconBg: 'bg-cyan-500',
        iconColor: 'text-white',
        accentColor: 'text-cyan-600',
        borderColor: 'border-t-cyan-500',
    },
    meeting: {
        icon: Video,
        label: 'Meeting',
        iconBg: 'bg-purple-500',
        iconColor: 'text-white',
        accentColor: 'text-purple-600',
        borderColor: 'border-t-purple-500',
    },
    default: {
        icon: Building,
        label: 'Activity',
        iconBg: 'bg-slate-500',
        iconColor: 'text-white',
        accentColor: 'text-slate-600',
        borderColor: 'border-t-slate-500',
    },
};
