'use client';

import { ComponentType } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { Clock, User } from 'lucide-react';
import { EmptyState } from './states';

export interface ActivityTimelineItem {
  id: string;
  type: string;
  title: string;
  description?: string;
  occurredAt: string;
  createdBy: { name: string };
  durationMinutes?: number;
  outcome?: string;
  isAutomated?: boolean;
  participants?: Array<{ name?: string }>;
}

export interface ActivityTimelineProps {
  activities: ActivityTimelineItem[];
  loading: boolean;
  emptyTitle?: string;
  emptyDescription?: string;
  onLoadMore?: () => void;
  hasMore?: boolean;
  activityIcons?: Record<string, ComponentType<any>>;
  activityColors?: Record<string, string>;
  formatTime?: (date: string) => string;
}

function defaultFormatTime(date: string): string {
  try {
    return formatDistanceToNow(new Date(date), { addSuffix: true });
  } catch {
    return '';
  }
}

export function ActivityTimeline({
  activities,
  loading,
  emptyTitle = 'No activities yet',
  emptyDescription = 'Log calls, meetings, and notes to track your interactions',
  onLoadMore,
  hasMore = false,
  activityIcons = {},
  activityColors = {},
  formatTime = defaultFormatTime,
}: ActivityTimelineProps) {
  if (loading) {
    return (
      <div className="space-y-4">
        {[...Array(3)].map((_, i) => (
          <div key={i} className="flex gap-4 animate-pulse">
            <div className="w-10 h-10 bg-gray-200 rounded-full" />
            <div className="flex-1">
              <div className="h-4 bg-gray-200 rounded w-1/3 mb-2" />
              <div className="h-3 bg-gray-200 rounded w-2/3" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Timeline */}
      <div className="relative">
        {/* Timeline line */}
        <div className="absolute left-5 top-0 bottom-0 w-0.5 bg-gray-200" />

        {/* Activities */}
        <div className="space-y-6">
          {activities.length === 0 ? (
            <EmptyState title={emptyTitle} description={emptyDescription} />
          ) : (
            activities.map((activity) => {
              const Icon = activityIcons[activity.type];
              const colorClass =
                activityColors[activity.type] || 'bg-gray-100 text-gray-600';

              return (
                <div key={activity.id} className="relative flex gap-4">
                  {/* Icon */}
                  <div
                    className={`relative z-10 flex items-center justify-center w-10 h-10 rounded-full ${colorClass}`}
                  >
                    {Icon ? <Icon className="w-5 h-5" /> : null}
                  </div>

                  {/* Content */}
                  <div className="flex-1 bg-white rounded-lg border border-gray-200 p-4">
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex-1">
                        <h4 className="font-medium text-gray-900">
                          {activity.title}
                        </h4>
                        {activity.description && (
                          <p className="text-sm text-gray-600 mt-1">
                            {activity.description}
                          </p>
                        )}
                      </div>
                      <div className="text-xs text-gray-500 ml-4 whitespace-nowrap">
                        {formatTime(activity.occurredAt)}
                      </div>
                    </div>

                    {/* Metadata */}
                    <div className="flex items-center gap-4 text-sm text-gray-600">
                      <div className="flex items-center gap-1">
                        <User className="w-3 h-3" />
                        {activity.createdBy.name}
                      </div>

                      {activity.durationMinutes && (
                        <div className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {activity.durationMinutes}m
                        </div>
                      )}

                      {activity.outcome && (
                        <div className="px-2 py-0.5 text-xs bg-gray-100 text-gray-700 rounded">
                          {activity.outcome.replace(/_/g, ' ')}
                        </div>
                      )}

                      {activity.isAutomated && (
                        <div className="text-xs text-gray-500 italic">
                          Auto-tracked
                        </div>
                      )}
                    </div>

                    {/* Participants */}
                    {activity.participants &&
                      activity.participants.length > 0 && (
                        <div className="mt-2 pt-2 border-t border-gray-100">
                          <div className="text-xs text-gray-500">
                            With:{' '}
                            {activity.participants
                              .map((p) => p.name)
                              .filter(Boolean)
                              .join(', ')}
                          </div>
                        </div>
                      )}
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>

      {/* Load More */}
      {hasMore && onLoadMore && (
        <div className="text-center pt-4">
          <button
            onClick={onLoadMore}
            className="px-4 py-2 text-sm text-primary hover:text-primary/80 hover:bg-primary/10 rounded-md transition-colors"
          >
            Load more activities
          </button>
        </div>
      )}
    </div>
  );
}
