'use client';

import { useLocale, useTranslations } from 'next-intl';
import { TreatmentDetailSummaryRow } from '@/components/ui/treatment/TreatmentDetailSummaryRow';
import { APP_DATE, formatAppDate } from '@/lib/i18n/format';
import type { LinkedOrganizationOption, PastTreatment } from '@/types/treatment';
import type { TreatmentCatalogEntry } from '@/types/treatment-catalog';

interface TreatmentPreviewCardProps {
  treatment: PastTreatment | null;
  /** e.g. "Current draft" or a formatted date label while browsing. */
  heading: string;
  labDependentCodes: Set<string>;
  treatmentCatalog: TreatmentCatalogEntry[];
  orgs?: LinkedOrganizationOption[];
  embedded?: boolean;
}

export function TreatmentPreviewCard({
  treatment,
  heading,
  labDependentCodes,
  treatmentCatalog,
  orgs,
  embedded = false,
}: TreatmentPreviewCardProps) {
  const locale = useLocale();
  const t = useTranslations('treatment');

  return (
    <div className={embedded ? 'space-y-3' : 'surface-card p-4 space-y-3'}>
      {heading ? <h3 className="text-sm font-semibold text-text-primary">{heading}</h3> : null}

      {!treatment ? (
        <p className="text-sm text-text-muted">{t('selectAppointment')}</p>
      ) : (
        <div className="border border-border/70 rounded-[var(--radius-md)] p-3 bg-background-secondary/40 space-y-2">
          {treatment.id !== 'current-draft' ? (
            <time
              className="text-xs text-text-muted tabular-nums block"
              dateTime={treatment.treatmentAt}
            >
              {formatAppDate(treatment.treatmentAt, locale, APP_DATE.withWeekday)}
            </time>
          ) : null}
          <div className="space-y-2 max-h-[min(280px,40vh)] overflow-y-auto pr-1">
            {treatment.details.length === 0 ? (
              <p className="text-xs text-text-muted">{t('noDetails')}</p>
            ) : (
              treatment.details.map((detail, idx) => (
                <TreatmentDetailSummaryRow
                  key={`${detail.clientId ?? detail.id}-${idx}`}
                  detail={detail}
                  detailNumber={idx + 1}
                  labDependentCodes={labDependentCodes}
                  treatmentCatalog={treatmentCatalog}
                  orgs={orgs}
                  compact
                />
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
