'use client';

import { useRef } from 'react';
import { useTranslations } from 'next-intl';
import { Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/shared/Button';
import { Dropdown } from '@/components/ui/shared/Dropdown';
import {
  autosaveStatusClass,
  labPendingBannerClass,
  labSentBannerClass,
  labBlockedBannerClass,
} 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';

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;
  onRemoveDetail?: (detailClientId: string) => void;
  onUploadFiles: (files: FileList | null) => void;
  /** Detail chips + Add detail (default true). */
  showChrome?: boolean;
  /** Type / notes / attachments fields (default true). */
  showFields?: boolean;
}

export function TreatmentDetailsEditor({
  details,
  activeDetailId,
  onActiveDetailChange,
  onDetailsChange,
  isDetailLocked,
  labDependentCodes,
  treatmentCatalog,
  disabled,
  canEdit,
  saveStatus,
  uploadBusy,
  onAddDetail,
  onRemoveDetail,
  onUploadFiles,
  showChrome = true,
  showFields = true,
}: TreatmentDetailsEditorProps) {
  const t = useTranslations('treatment');
  const tCommon = useTranslations('common');
  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,
  );

  if (!showChrome && !showFields) return null;

  return (
    <div className="surface-card p-3 sm:p-4 space-y-4">
      {showChrome ? (
        <>
          <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) => {
              const detailLocked = isDetailLocked(d);
              const isActive = d.clientId === activeDetailId;
              // Same rules as the former Content-step delete button:
              // only when more than one detail remains; disabled if no edit, day-locked, sent, or uploading.
              const showRemoveAction = details.length > 1;
              const removeDisabled =
                !canEdit || disabled || detailLocked || uploadBusy;
              return (
                <div
                  key={d.clientId}
                  className={`
                    inline-flex items-stretch overflow-hidden rounded-[var(--radius-md)] border
                    ${
                      isActive
                        ? 'border-primary bg-primary-soft'
                        : 'border-border/70 hover:border-border hover:bg-background-card/50'
                    }
                  `}
                >
                  <button
                    type="button"
                    onClick={() => onActiveDetailChange(d.clientId)}
                    className={`
                      px-3 py-1.5 text-sm transition-colors
                      focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary/45
                      ${isActive ? 'font-medium text-text-primary' : 'text-text-secondary'}
                    `}
                  >
                    {t('detailLabel', { n: idx + 1 })}
                    {detailLocked ? ` · ${t('detailSentBadge')}` : ''}
                  </button>
                  {showRemoveAction ? (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        if (removeDisabled) return;
                        onRemoveDetail?.(d.clientId);
                      }}
                      disabled={removeDisabled}
                      title={tCommon('delete')}
                      aria-label={t('removeDetailAria', { n: idx + 1 })}
                      className={`
                        inline-flex items-center justify-center border-s px-1.5 transition-colors
                        focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-red-500/40
                        disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-inherit
                        ${
                          isActive
                            ? 'border-primary/30 text-text-muted hover:bg-red-500/15 hover:text-red-600'
                            : 'border-border/60 text-text-muted hover:bg-red-500/15 hover:text-red-600'
                        }
                      `}
                    >
                      <Trash2 className="h-3.5 w-3.5" aria-hidden />
                    </button>
                  ) : null}
                </div>
              );
            })}
          </div>
        </>
      ) : null}

      {showFields ? (
        <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>
          )}

          <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>

          <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={2}
              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-[60px]"
            />
          </label>

          <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>
      ) : null}

      {showFields && 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>
  );
}
