'use client';

import { useMemo, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles';
import { TreatmentHistoryDetailLine } from '@/components/ui/treatment/TreatmentHistoryDetailLine';
import { DetailLabSendBadge } from '@/components/ui/treatment/DetailLabSendBadge';
import { filterTreatmentHistoryItems } from '@/components/treatment/treatmentHistoryFilters';
import { AppDateInput } from '@/components/ui/shared/AppDateInput';
import { APP_DATE, formatAppDateTime } from '@/lib/i18n/format';
import type { LinkedOrganizationOption, PastTreatment } from '@/types/treatment';
import type { TreatmentCatalogEntry } from '@/types/treatment-catalog';

interface PastTreatmentsPanelProps {
  items: PastTreatment[];
  patientName?: string;
  currentAppointmentId?: string | null;
  treatmentCatalog: TreatmentCatalogEntry[];
  labDependentCodes: Set<string>;
  orgs?: LinkedOrganizationOption[];
  loading?: boolean;
  selectedPreviewId?: string | null;
  onSelectTreatment?: (treatment: PastTreatment) => void;
  compact?: boolean;
}

function formatHistoryTimestamp(iso: string, locale: string): string {
  return formatAppDateTime(iso, locale, APP_DATE.history);
}

export function PastTreatmentsPanel({
  items,
  patientName,
  currentAppointmentId,
  treatmentCatalog,
  labDependentCodes,
  orgs,
  loading,
  selectedPreviewId,
  onSelectTreatment,
  compact = false,
}: PastTreatmentsPanelProps) {
  const locale = useLocale();
  const t = useTranslations('treatment');
  const [notShippedOnly, setNotShippedOnly] = useState(false);
  const [filterDate, setFilterDate] = useState('');
  const [filtersOpen, setFiltersOpen] = useState(false);

  const hasActiveFilters = notShippedOnly || Boolean(filterDate);

  const displayedItems = useMemo(
    () =>
      filterTreatmentHistoryItems(items, labDependentCodes, {
        notShippedOnly,
        date: filterDate,
      }, currentAppointmentId),
    [items, currentAppointmentId, labDependentCodes, notShippedOnly, filterDate],
  );

  function clearFilters() {
    setNotShippedOnly(false);
    setFilterDate('');
  }

  const filterInputClass = `${FORM_SELECT_CLASS} rounded-md py-1.5 text-xs min-w-[9.5rem]`;

  const filtersBlock = (
    <div
      className={`flex flex-wrap items-center gap-x-3 gap-y-2 rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/30 ${
        compact ? 'p-2' : 'p-2.5'
      }`}
    >
      <Checkbox
        checked={notShippedOnly}
        onChange={setNotShippedOnly}
        label={t('historyFilterNotShipped')}
        className="text-xs [&_span:last-child]:text-xs shrink-0"
      />
      <label className="flex items-center gap-1.5 shrink-0">
        <span className="text-xs font-medium text-text-muted whitespace-nowrap">
          {t('historyFilterDate')}
        </span>
        <AppDateInput
          value={filterDate}
          onChange={setFilterDate}
          className={filterInputClass}
        />
      </label>
      <Button
        variant="ghost"
        size="sm"
        onClick={clearFilters}
        disabled={!hasActiveFilters}
        className="shrink-0"
      >
        {t('historyClearFilters')}
      </Button>
    </div>
  );

  const listBlock = (
    <>
      {loading && <p className="text-xs text-text-muted">{t('loadingHistory')}</p>}

      {!loading && displayedItems.length === 0 && (
        <p className="text-xs text-text-muted">
          {hasActiveFilters ? t('historyFilterEmpty') : t('historyEmpty')}
        </p>
      )}

      <div
        className={`space-y-1 overflow-y-auto overscroll-y-contain pr-1 ${
          compact ? 'max-h-[min(220px,32vh)]' : 'max-h-[min(420px,50vh)]'
        }`}
      >
        {displayedItems.map((treatment) => {
          const isSelected = selectedPreviewId === treatment.id;

          return (
            <article
              key={treatment.id}
              role="button"
              tabIndex={0}
              onClick={() => onSelectTreatment?.(treatment)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onSelectTreatment?.(treatment);
                }
              }}
              className={`
                border rounded-[var(--radius-sm)] px-2 py-1.5 cursor-pointer transition-colors
                focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/45
                ${
                  isSelected
                    ? 'border-primary bg-primary/5'
                    : 'border-border/60 bg-background-secondary/30 hover:border-border hover:bg-background-secondary/50'
                }
              `}
            >
              <div className="flex flex-wrap items-center gap-2">
                <time
                  className="text-xs font-medium text-text-primary tabular-nums"
                  dateTime={treatment.treatmentAt}
                >
                  {formatHistoryTimestamp(treatment.treatmentAt, locale)}
                </time>
              </div>

              {treatment.details.length === 0 ? (
                <p className="text-[10px] text-text-muted mt-1">{t('noDetails')}</p>
              ) : (
                <div className="mt-1.5 divide-y divide-border/50 border-t border-border/40 pointer-events-none">
                  {treatment.details.map((detail, idx) => (
                    <div key={`${detail.clientId ?? detail.id}-${idx}`} className="py-1.5 space-y-1">
                      <TreatmentHistoryDetailLine
                        detail={detail}
                        detailNumber={idx + 1}
                        treatmentCatalog={treatmentCatalog}
                      />
                      <DetailLabSendBadge
                        detail={detail}
                        labDependentCodes={labDependentCodes}
                        orgs={orgs}
                        className="text-[10px] px-1.5 py-0"
                      />
                    </div>
                  ))}
                </div>
              )}
            </article>
          );
        })}
      </div>
    </>
  );

  if (compact) {
    return (
      <div className="space-y-2 pt-2">
        <button
          type="button"
          onClick={() => setFiltersOpen((open) => !open)}
          className="text-[10px] font-medium text-primary hover:underline"
        >
          {filtersOpen ? t('historyHideFilters') : t('historyShowFilters')}
        </button>
        {filtersOpen ? filtersBlock : null}
        {listBlock}
      </div>
    );
  }

  return (
    <div className="surface-card p-4 space-y-3">
      <div>
        <h3 className="text-sm font-semibold text-text-primary">
          {patientName ? t('historyPatientScope', { patientName }) : t('historyTitle')}
        </h3>
        <p className="text-[11px] text-text-muted mt-0.5">{t('historySubtitle')}</p>
      </div>
      {filtersBlock}
      {listBlock}
    </div>
  );
}
