'use client';

import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { CaseTaskProgressBar } from '@/components/ui/lab/CaseDetailPanel';
import { LabCaseDueDateBadge } from '@/components/lab/LabCaseDueDateBadge';
import { LabCaseActivityFeed } from '@/components/ui/treatment/LabCaseActivityFeed';
import { formatLabCaseActivityLine } from '@/lib/labCaseActivityLabels';
import { notificationsApi } from '@/lib/api/notifications';
import { notifyTabBadgesChanged } from '@/lib/tabBadgeUtils';
import type { PatientLabCaseSummary } from '@/types/lab-case-activity';

interface LabCaseTrackerCardProps {
  summary: PatientLabCaseSummary;
  locale: string;
  onSummaryChange?: (summary: PatientLabCaseSummary) => void;
  onMarkedRead?: (labCaseId: string) => void;
}

export function LabCaseTrackerCard({
  summary,
  locale,
  onSummaryChange,
  onMarkedRead,
}: LabCaseTrackerCardProps) {
  const t = useTranslations('treatment');
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    if (!expanded || !summary.hasUnread) return;
    void notificationsApi.markCaseRead(summary.labCaseId).then(() => {
      notifyTabBadgesChanged();
      onSummaryChange?.({ ...summary, hasUnread: false });
      onMarkedRead?.(summary.labCaseId);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps -- mark read once per expand
  }, [expanded, summary.labCaseId, summary.hasUnread, onSummaryChange, onMarkedRead]);

  const lastLine = summary.lastActivity
    ? formatLabCaseActivityLine(summary.lastActivity, t, locale)
    : null;

  return (
    <div className="rounded-md border border-border bg-background-secondary/30 p-3 space-y-2">
      <div className="flex items-start gap-2">
        <div className="min-w-0 flex-1 space-y-1">
          <div className="flex flex-wrap items-center gap-1.5">
            <p className="text-sm font-medium text-text-primary">{summary.labName}</p>
            <LabCaseDueDateBadge
              dueDate={summary.dueDate}
              locale={locale}
              className="text-[10px]"
            />
            {summary.isOverdue ? (
              <span className="text-[10px] font-medium text-badge-danger-fg">{t('overdueBadge')}</span>
            ) : null}
          </div>
          <CaseTaskProgressBar
            completed={summary.taskProgress.completed}
            total={summary.taskProgress.total}
          />
          {lastLine ? (
            <p className="text-[11px] text-text-muted line-clamp-2">{lastLine}</p>
          ) : null}
        </div>
        {summary.hasUnread ? (
          <span
            className="mt-1 h-2 w-2 shrink-0 rounded-full bg-badge-warning-fg"
            aria-label={t('unreadLabCase')}
          />
        ) : null}
      </div>

      <button
        type="button"
        onClick={() => setExpanded((open) => !open)}
        className="text-xs font-medium text-primary hover:underline"
      >
        {expanded ? t('labTrackerCollapse') : t('labTrackerExpand')}
      </button>

      {expanded ? (
        <div className="space-y-2 border-t border-border/60 pt-3">
          <p className="text-xs font-medium text-text-secondary">{t('activityFeedTitle')}</p>
          <LabCaseActivityFeed labCaseId={summary.labCaseId} locale={locale} />
        </div>
      ) : null}
    </div>
  );
}
