'use client';

import { useQuery } from '@tanstack/react-query';
import { formatDistanceToNow } from 'date-fns';

import { apiFetch } from '@/lib/api/client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { WidgetErrorBoundary } from './widget-error-boundary';

interface ActivityItem {
  id: string;
  action: string;
  entityType: string;
  entityId: string | null;
  userId: string | null;
  metadata: Record<string, unknown> | null;
  createdAt: string;
}

const ACTION_VARIANTS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  create: 'default',
  update: 'secondary',
  delete: 'destructive',
  archive: 'outline',
  restore: 'secondary',
};

function ActionBadge({ action }: { action: string }) {
  const variant = ACTION_VARIANTS[action] ?? 'outline';
  return (
    <Badge variant={variant} className="shrink-0 capitalize text-xs">
      {action}
    </Badge>
  );
}

function ActivityFeedInner() {
  const { data, isLoading } = useQuery<ActivityItem[]>({
    queryKey: ['dashboard', 'activity'],
    queryFn: () => apiFetch<ActivityItem[]>('/api/v1/dashboard/activity'),
    staleTime: 30_000,
    retry: 2,
  });

  if (isLoading) {
    return <CardSkeleton />;
  }

  const items = data ?? [];

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Recent Activity</CardTitle>
      </CardHeader>
      <CardContent>
        {items.length === 0 ? (
          <p className="text-sm text-muted-foreground">No recent activity.</p>
        ) : (
          <div className="max-h-80 overflow-y-auto space-y-3 pr-1">
            {items.map((item) => (
              <div
                key={item.id}
                className="flex items-start gap-3 text-sm border-b border-border pb-3 last:border-0 last:pb-0"
              >
                <ActionBadge action={item.action} />
                <div className="min-w-0 flex-1">
                  <p className="truncate text-foreground">
                    <span className="font-medium capitalize">{item.entityType}</span>
                    {item.entityId && (
                      <span className="ml-1 text-muted-foreground font-mono text-xs">
                        {item.entityId.slice(0, 8)}
                      </span>
                    )}
                  </p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {formatDistanceToNow(new Date(item.createdAt), { addSuffix: true })}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

export function ActivityFeed() {
  return (
    <WidgetErrorBoundary>
      <ActivityFeedInner />
    </WidgetErrorBoundary>
  );
}
