'use client';

import { useEffect } from 'react';
import { LabCaseCommentsPanel } from '@/components/ui/lab/LabCaseCommentsPanel';
import { treatmentsApi } from '@/lib/api/treatments';
import { notificationsApi } from '@/lib/api/notifications';
import { notifyTabBadgesChanged } from '@/lib/tabBadgeUtils';

interface DetailLabCaseCommentsSectionProps {
  labCaseId: string;
  canPost: boolean;
  deferSubmit?: boolean;
  composerValue?: string;
  onComposerValueChange?: (value: string) => void;
  onError?: (message: string) => void;
  onMarkRead?: (labCaseId: string) => void;
  onActivityChange?: () => void;
}

export function DetailLabCaseCommentsSection({
  labCaseId,
  canPost,
  deferSubmit = false,
  composerValue,
  onComposerValueChange,
  onError,
  onMarkRead,
  onActivityChange,
}: DetailLabCaseCommentsSectionProps) {
  useEffect(() => {
    if (!labCaseId) return;
    void notificationsApi.markCaseRead(labCaseId).then(() => {
      notifyTabBadgesChanged();
      onMarkRead?.(labCaseId);
    });
  }, [labCaseId, onMarkRead]);

  return (
    <div className="border-t border-border/60 pt-4">
      <LabCaseCommentsPanel
        caseId={labCaseId}
        canPost={canPost}
        canToggleVisibility={false}
        deferSubmit={deferSubmit}
        composerValue={composerValue}
        onComposerValueChange={onComposerValueChange}
        loadComments={async () => {
          const response = await treatmentsApi.listLabCaseComments(labCaseId);
          return response.data;
        }}
        onPost={async (body) => {
          const response = await treatmentsApi.addLabCaseComment(labCaseId, { body });
          notifyTabBadgesChanged();
          onActivityChange?.();
          return response.data;
        }}
        onError={onError}
      />
    </div>
  );
}
