"use client";

import { useMemo } from "react";
import { ArrowTrendingUpIcon } from "@heroicons/react/24/outline";
import type { Activity } from "@customer-portal/domain/dashboard";
import { DashboardActivityItem } from "./DashboardActivityItem";
import { isSameDay, isToday, isYesterday } from "@/shared/utils";

interface ActivityTimelineProps {
  activities: Activity[];
  onItemClick?: (activity: Activity) => void;
  maxItems?: number;
}

interface GroupedActivities {
  label: string;
  date: Date;
  activities: Activity[];
}

function formatDateLabel(date: Date): string {
  if (isToday(date)) {
    return "Today";
  }
  if (isYesterday(date)) {
    return "Yesterday";
  }
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

function groupActivitiesByDate(activities: Activity[]): GroupedActivities[] {
  const groups: GroupedActivities[] = [];

  for (const activity of activities) {
    const activityDate = new Date(activity.date);
    const existingGroup = groups.find(g => isSameDay(g.date, activityDate));

    if (existingGroup) {
      existingGroup.activities.push(activity);
    } else {
      groups.push({
        label: formatDateLabel(activityDate),
        date: activityDate,
        activities: [activity],
      });
    }
  }

  // Sort groups by date (newest first)
  return groups.sort((a, b) => b.date.getTime() - a.date.getTime());
}

export function ActivityTimeline({
  activities,
  onItemClick,
  maxItems = 10,
}: ActivityTimelineProps) {
  const groupedActivities = useMemo(() => {
    const limited = activities.slice(0, maxItems);
    return groupActivitiesByDate(limited);
  }, [activities, maxItems]);

  if (activities.length === 0) {
    return (
      <div className="text-center py-12">
        <div className="w-12 h-12 rounded-xl bg-muted/50 flex items-center justify-center mx-auto mb-3">
          <ArrowTrendingUpIcon className="h-6 w-6 text-muted-foreground/40" />
        </div>
        <h3 className="text-sm font-medium text-foreground">No recent activity</h3>
        <p className="mt-1 text-sm text-muted-foreground max-w-xs mx-auto">
          Your account activity will appear here once you start using our services.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {groupedActivities.map(group => (
        <div key={group.label}>
          {/* Date header */}
          <div className="flex items-center gap-3 mb-3">
            <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
              {group.label}
            </span>
            <div className="flex-1 h-px bg-border" />
          </div>

          {/* Activities for this date */}
          <div className="space-y-0">
            {group.activities.map((activity, index) => {
              const isClickable =
                activity.type === "invoice_created" || activity.type === "invoice_paid";
              const isLastInGroup = index === group.activities.length - 1;

              return (
                <DashboardActivityItem
                  key={activity.id}
                  activity={activity}
                  onClick={isClickable && onItemClick ? () => onItemClick(activity) : undefined}
                  showConnector={!isLastInGroup}
                />
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}
