'use client';

import { useCallback, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { formatLabCaseActivityLine } from '@/lib/labCaseActivityLabels';
import { notificationsApi } from '@/lib/api/notifications';
import type { LabCaseActivityItem } from '@/types/lab-case-activity';

interface LabCaseActivityFeedProps {
  labCaseId: string;
  locale: string;
  className?: string;
}

export function LabCaseActivityFeed({ labCaseId, locale, className }: LabCaseActivityFeedProps) {
  const t = useTranslations('treatment');
  const tCommon = useTranslations('common');
  const [items, setItems] = useState<LabCaseActivityItem[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const response = await notificationsApi.listLabCaseActivities(labCaseId);
      setItems(response.data ?? []);
    } catch {
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [labCaseId]);

  useEffect(() => {
    void load();
  }, [load]);

  if (loading) {
    return <p className={`text-xs text-text-muted ${className ?? ''}`}>{tCommon('loading')}</p>;
  }

  if (items.length === 0) {
    return <p className={`text-xs text-text-muted ${className ?? ''}`}>{t('activityFeedEmpty')}</p>;
  }

  return (
    <ul className={`space-y-2 ${className ?? ''}`}>
      {items.map((item) => (
        <li
          key={item.id}
          className="rounded-md border border-border/70 bg-background-secondary/40 px-3 py-2 text-xs text-text-secondary"
        >
          {formatLabCaseActivityLine(item, t, locale)}
        </li>
      ))}
    </ul>
  );
}
