"use client"

import * as React from "react"
import { Clock, RefreshCw } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { cn } from "@/lib/utils"

export type ActivityTimelineEventKind =
    | "stage"
    | "activity"
    | "note"
    | "reminder"
    | "timeline"

export interface ActivityTimelineEvent {
    id: string
    type?: ActivityTimelineEventKind
    title: string
    description?: string
    date: string
    author?: string
    meta?: string
    color: string
    icon: React.ReactNode
}

export interface ActivityTimelinePanelProps {
    events: ActivityTimelineEvent[]
    isLoading?: boolean
    title?: string
    /** Badge text, e.g. "6 events". Defaults from `events.length`. */
    countLabel?: string
    emptyTitle?: string
    emptyDescription?: string
    className?: string
    /**
     * When true, the scrollable list grows with a flex parent (`flex-1 min-h-0`) instead of a fixed max-height.
     */
    fillHeight?: boolean
}

function formatTimelineDate(iso: string) {
    return new Date(iso).toLocaleString(undefined, {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
    })
}

function accentTint(accent: string): string {
    if (accent.length === 7 && accent.startsWith("#")) {
        return `${accent}18`
    }
    return "rgba(148, 163, 184, 0.14)"
}

function TimelineEntryCard({ event }: { event: ActivityTimelineEvent }) {
    const accent = event.color?.trim() || "#94a3b8"

    return (
        <article
            className={cn(
                "rounded-xl border border-border/50 bg-white/95 px-4 py-3.5 shadow-sm transition-all",
                "hover:border-border/80 hover:shadow-md",
            )}
            style={{ borderLeftWidth: 3, borderLeftColor: accent }}
        >
            <div className="flex gap-3.5">
                <div
                    className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-black/[0.04]"
                    style={{ backgroundColor: accentTint(accent), color: accent }}
                >
                    <span className="flex items-center justify-center [&_svg]:size-[15px]">
                        {event.icon}
                    </span>
                </div>
                <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-1">
                        <h3 className="text-[13px] font-semibold leading-snug tracking-tight text-foreground">
                            {event.title}
                        </h3>
                        {event.meta ? (
                            <Badge
                                variant="outline"
                                className="h-5 shrink-0 border-border/80 text-[10px] font-semibold"
                            >
                                {event.meta}
                            </Badge>
                        ) : null}
                    </div>
                    {event.description ? (
                        <p className="mt-1.5 line-clamp-3 text-[12px] leading-relaxed text-muted-foreground">
                            {event.description}
                        </p>
                    ) : null}
                    <div className="mt-2.5 flex flex-wrap items-center gap-x-2 text-[11px] text-muted-foreground">
                        <time dateTime={event.date} className="tabular-nums">
                            {formatTimelineDate(event.date)}
                        </time>
                        {event.author ? (
                            <>
                                <span className="text-border" aria-hidden>
                                    ·
                                </span>
                                <span className="max-w-[220px] truncate">{event.author}</span>
                            </>
                        ) : null}
                    </div>
                </div>
            </div>
        </article>
    )
}

export function ActivityTimelinePanel({
    events,
    isLoading = false,
    title = "Activity Timeline",
    countLabel,
    emptyTitle = "No activity yet",
    emptyDescription = "Activities, notes, and stage changes will appear here.",
    className,
    fillHeight = false,
}: ActivityTimelinePanelProps) {
    const badgeText = countLabel ?? `${events.length} events`

    return (
        <div
            className={cn(
                "flex min-h-0 flex-col overflow-hidden rounded-2xl border border-white/40 bg-white/50 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] backdrop-blur-[15px]",
                className,
            )}
        >
            <div className="flex shrink-0 items-center gap-2 border-b border-border/60 px-5 py-4">
                <Clock size={15} className="shrink-0 text-accent" aria-hidden />
                <h2 className="font-['Lexend'] text-[13px] font-bold text-gray-800">{title}</h2>
                <Badge variant="secondary" className="ml-auto shrink-0 text-[10px]">
                    {badgeText}
                </Badge>
                {isLoading ? (
                    <RefreshCw
                        size={12}
                        className="shrink-0 animate-spin text-muted-foreground"
                        aria-hidden
                    />
                ) : null}
            </div>

            <div
                className={cn(
                    "min-h-[200px] overflow-y-auto overflow-x-hidden overscroll-contain p-4 md:p-5 scrollbar-themed",
                    fillHeight ? "max-h-none min-h-0 flex-1" : "max-h-[min(52vh,560px)]",
                )}
                role="region"
                aria-label={`${title} list`}
            >
                {events.length === 0 ? (
                    <div className="flex min-h-[min(240px,40vh)] flex-col items-center justify-center py-10 text-center md:py-14">
                        <Clock size={34} className="mb-3 text-muted-foreground/30" aria-hidden />
                        <p className="text-[13px] font-semibold text-muted-foreground">{emptyTitle}</p>
                        <p className="mt-1 max-w-xs text-[11px] text-muted-foreground/80">
                            {emptyDescription}
                        </p>
                    </div>
                ) : (
                    <div className="flex flex-col gap-2.5 pr-0.5">
                        {events.map((event) => (
                            <TimelineEntryCard key={event.id} event={event} />
                        ))}
                    </div>
                )}
            </div>
        </div>
    )
}
