'use client';

import React, { useEffect, useState } from 'react';
import { Button } from '@/ui/Button';
import { FeedItem } from '@/ui/FeedItem';

interface FeedItemData {
  id: string;
  type: string;
  headline: string;
  body?: string;
  timestamp: string;
  formattedTime: string;
  ctaHref?: string;
  ctaLabel?: string;
}

function timeAgo(timestamp: Date | string): string {
  const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp;
  const diffMs = Date.now() - date.getTime();
  const diffMinutes = Math.floor(diffMs / 60000);
  if (diffMinutes < 1) return 'Just now';
  if (diffMinutes < 60) return `${diffMinutes} min ago`;
  const diffHours = Math.floor(diffMinutes / 60);
  if (diffHours < 24) return `${diffHours} h ago`;
  const diffDays = Math.floor(diffHours / 24);
  return `${diffDays} d ago`;
}

async function resolveActor() {
  return null;
}

interface FeedItemCardProps {
  item: FeedItemData;
}

export function FeedItemCard({ item }: FeedItemCardProps) {
  const [actor, setActor] = useState<{ name: string; avatarUrl: string } | null>(null);

  useEffect(() => {
    let cancelled = false;

    void (async () => {
      const resolved = await resolveActor();
      if (!cancelled) {
        setActor(resolved);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [item]);

  return (
    <FeedItem
      actorName={actor?.name}
      actorAvatarUrl={actor?.avatarUrl}
      typeLabel={item.type.startsWith('friend') ? 'FR' : 'LG'}
      headline={item.headline}
      body={item.body}
      timeAgo={timeAgo(item.timestamp)}
      cta={item.ctaHref && item.ctaLabel ? (
        <Button
          as="a"
          href={item.ctaHref}
          variant="secondary"
          size="sm"
          px={4}
          py={2}
        >
          {item.ctaLabel}
        </Button>
      ) : undefined}
    />
  );
}
