'use client';

import { useRef } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { Dropdown } from '@/components/ui/shared/Dropdown';
import {
  autosaveStatusClass,
  labPendingBannerClass,
  labSentBannerClass,
} from '@/components/treatment/treatmentStatusStyles';
import type { TreatmentDetailDraft } from '@/types/treatment';
import type { TreatmentCatalogEntry } from '@/types/treatment-catalog';
import { treatmentTypeColor } from '@/components/shared/treatmentTypeDisplay';
import {
  isDetailReadyForLabDispatch,
  isDetailTypeSelected,
  isLabDependentDetailMissingTeeth,
} from '@/components/treatment/treatmentDetailRules';
import { labBlockedBannerClass } from '@/components/treatment/treatmentStatusStyles';

interface TreatmentDetailsEditorProps {
  details: TreatmentDetailDraft[];
  activeDetailId: string;
  onActiveDetailChange: (id: string) => void;
  onDetailsChange: (details: TreatmentDetailDraft[]) => void;
  isDetailLocked: (detail: TreatmentDetailDraft) => boolean;
  labDependentCodes: Set<string>;
  treatmentCatalog: TreatmentCatalogEntry[];
  disabled: boolean;
  canEdit: boolean;
  saveStatus: 'idle' | 'dirty' | 'saving' | 'saved' | 'error';
  uploadBusy: boolean;
  onAddDetail: () => void;
  onUploadFiles: (files: FileList | null) => void;
}

export function TreatmentDetailsEditor({
  details,
  activeDetailId,
  onActiveDetailChange,
  onDetailsChange,
  isDetailLocked,
  labDependentCodes,
  treatmentCatalog,
  disabled,
  canEdit,
  saveStatus,
  uploadBusy,
  onAddDetail,
  onUploadFiles,
}: TreatmentDetailsEditorProps) {
  const t = useTranslations('treatment');
  const attachmentInputRef = useRef<HTMLInputElement>(null);
  const activeDetail = details.find((d) => d.clientId === activeDetailId) ?? details[0];

  if (!activeDetail) return null;

  const locked = isDetailLocked(activeDetail);
  const readOnly = disabled || locked;
  const treatmentTypeTextColor = isDetailTypeSelected(activeDetail)
    ? treatmentTypeColor(
        activeDetail.treatmentType,
        treatmentCatalog.findIndex((e) => e.code === activeDetail.treatmentType),
      )
    : undefined;
  const showPendingLabHint =
    isDetailReadyForLabDispatch(activeDetail, labDependentCodes) && !locked && !readOnly;
  const showMissingTeethLabBlock = isLabDependentDetailMissingTeeth(
    activeDetail,
    labDependentCodes,
  );

  return (
    <div className="surface-card p-3 sm:p-4 space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
        <div>
          <h3 className="text-sm font-semibold text-text-primary">{t('detailsTitle')}</h3>
          <p className="text-xs text-text-muted mt-0.5">{t('detailsSubtitle')}</p>
        </div>
        <Button
          type="button"
          variant="primary"
          disabled={!canEdit || disabled}
          onClick={onAddDetail}
          fullWidth
          className="sm:w-auto shrink-0"
        >
          {t('addDetail')}
        </Button>
      </div>

      <div className="flex flex-wrap gap-2">
        {details.map((d, idx) => (
          <button
            key={d.clientId}
            type="button"
            onClick={() => onActiveDetailChange(d.clientId)}
            className={`
              rounded-[var(--radius-md)] border px-3 py-1.5 text-sm transition-colors
              focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/45
              ${
                d.clientId === activeDetailId
                  ? 'border-primary bg-primary-soft font-medium text-text-primary'
                  : 'border-border/70 text-text-secondary hover:border-border hover:bg-background-card/50'
              }
            `}
          >
            {t('detailLabel', { n: idx + 1 })}
            {isDetailLocked(d) ? ` · ${t('detailSentBadge')}` : ''}
          </button>
        ))}
      </div>

      <div className="space-y-4 border border-border/60 rounded-[var(--radius-md)] p-4 bg-background-secondary/30">
        {locked && (
          <p className={labSentBannerClass}>{t('detailLockedInShipment')}</p>
        )}
        {showPendingLabHint && (
          <p className={labPendingBannerClass}>{t('detailPendingLabSend')}</p>
        )}
        {showMissingTeethLabBlock && (
          <p className={labBlockedBannerClass}>{t('labShipmentBlockedBody')}</p>
        )}

        <label className="block text-xs font-medium text-text-secondary">
          {t('comments')}
          <textarea
            value={activeDetail.comment}
            onChange={(e) => {
              const v = e.target.value;
              onDetailsChange(
                details.map((d) => (d.clientId === activeDetailId ? { ...d, comment: v } : d)),
              );
            }}
            placeholder={t('commentsPlaceholder')}
            rows={5}
            disabled={readOnly}
            className="mt-1.5 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35 resize-y min-h-[120px]"
          />
        </label>

        <div>
          <Dropdown
            label={t('treatmentType')}
            value={activeDetail.treatmentType}
            onChange={(e) => {
              const nextType = e.target.value as TreatmentDetailDraft['treatmentType'];
              onDetailsChange(
                details.map((d) =>
                  d.clientId === activeDetailId ? { ...d, treatmentType: nextType } : d,
                ),
              );
            }}
            disabled={readOnly}
            style={{ color: treatmentTypeTextColor }}
          >
            <option value="">{t('treatmentTypePlaceholder')}</option>
            {treatmentCatalog.map((entry, index) => (
              <option
                key={entry.code}
                value={entry.code}
                style={{
                  color: treatmentTypeColor(entry.code, index),
                  backgroundColor: '#14253d',
                }}
              >
                {entry.label}
              </option>
            ))}
          </Dropdown>
        </div>

        <div>
          <p className="text-xs font-medium text-text-secondary mb-2">{t('attachments')}</p>
          <input
            ref={attachmentInputRef}
            id="treatment-detail-attachments"
            type="file"
            multiple
            disabled={readOnly || uploadBusy}
            onChange={(e) => {
              onUploadFiles(e.target.files);
              e.target.value = '';
            }}
            className="sr-only"
            aria-label={t('attachFiles')}
          />
          <Button
            type="button"
            variant="primary"
            disabled={readOnly || uploadBusy}
            isLoading={uploadBusy}
            onClick={() => attachmentInputRef.current?.click()}
            aria-controls="treatment-detail-attachments"
          >
            {t('chooseFiles')}
          </Button>
          {activeDetail.attachmentMetas.length > 0 && (
            <ul className="mt-2 space-y-1 text-xs text-text-muted">
              {activeDetail.attachmentMetas.map((f) => (
                <li key={f.id} className="truncate">
                  {f.fileName} ({(f.sizeBytes / 1024).toFixed(1)} KB)
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      {canEdit && saveStatus !== 'idle' && (
        <p
          className={`text-xs pt-2 border-t border-border/60 ${autosaveStatusClass(saveStatus)}`}
          role="status"
          aria-live="polite"
        >
          {saveStatus === 'dirty' && t('unsavedChanges')}
          {saveStatus === 'saving' && t('saveStatusSaving')}
          {saveStatus === 'saved' && t('saveStatusSaved')}
          {saveStatus === 'error' && t('saveStatusError')}
        </p>
      )}
    </div>
  );
}
