'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 type { TreatmentDetailDraft } from '@/types/treatment';
import { TREATMENT_TYPE_COLORS, treatmentTypeLabelKey } from '@/components/ui/treatment/treatmentTypeDisplay';

interface TreatmentDetailsEditorProps {
  details: TreatmentDetailDraft[];
  activeDetailId: string;
  onActiveDetailChange: (id: string) => void;
  onDetailsChange: (details: TreatmentDetailDraft[]) => void;
  isDetailLocked: (detail: TreatmentDetailDraft) => boolean;
  disabled: boolean;
  canEdit: boolean;
  isDirty: boolean;
  saveBusy: boolean;
  uploadBusy: boolean;
  onAddDetail: () => void;
  onPreview: () => void;
  onSave: () => void;
  onUploadFiles: (files: FileList | null) => void;
}

export function TreatmentDetailsEditor({
  details,
  activeDetailId,
  onActiveDetailChange,
  onDetailsChange,
  isDetailLocked,
  disabled,
  canEdit,
  isDirty,
  saveBusy,
  uploadBusy,
  onAddDetail,
  onPreview,
  onSave,
  onUploadFiles,
}: 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 = TREATMENT_TYPE_COLORS[activeDetail.treatmentType];

  return (
    <div className="surface-card p-4 space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <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>
        <div className="flex flex-wrap items-center gap-2">
          <Button type="button" variant="secondary" disabled={!canEdit || disabled} onClick={onPreview}>
            {tCommon('preview')}
          </Button>
          <Button type="button" variant="primary" disabled={!canEdit || disabled} onClick={onAddDetail}>
            {t('addDetail')}
          </Button>
        </div>
      </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="text-xs text-text-muted rounded-[var(--radius-sm)] border border-border/50 bg-background-secondary/50 px-2 py-1.5">
            {t('detailLockedInShipment')}
          </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}
            className="capitalize"
            style={{ color: treatmentTypeTextColor }}
          >
            <option value="consultation" style={{ color: '#ddd6fe', backgroundColor: '#14253d' }} className="capitalize">{t('typeConsultation')}</option>
            <option value="filling" style={{ color: '#fed7aa', backgroundColor: '#14253d' }} className="capitalize">{t('typeFilling')}</option>
            <option value="endo" style={{ color: '#fecaca', backgroundColor: '#14253d' }} className="capitalize">{t('typeEndo')}</option>
            <option value="visit" style={{ color: '#bae6fd', backgroundColor: '#14253d' }} className="capitalize">{t('typeVisit')}</option>
            <option value="hygiene" style={{ color: '#d9f99d', backgroundColor: '#14253d' }} className="capitalize">{t('typeHygiene')}</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 && (
        <div className="flex flex-wrap gap-3 pt-2 border-t border-border/60">
          <Button
            type="button"
            variant="primary"
            disabled={disabled || saveBusy}
            isLoading={saveBusy}
            onClick={onSave}
          >
            {t('saveDraft')}
          </Button>
          <p className="text-xs text-text-muted self-center">
            {isDirty ? t('unsavedChanges') : t('draftSaved')}. {t('detailsSaveHint')}
          </p>
        </div>
      )}
    </div>
  );
}
