import React, { useCallback, useId, useMemo, useRef, useState } from 'react';
import { Pencil } from 'lucide-react';
import { SingleDateCalendarPanel } from './SingleDateCalendarPanel';
import { SingleYearPickerPanel } from './SingleYearPickerPanel';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';
import { buildYearOptions, formatDateYmd, isEmpty } from '../utils/vehicle';

interface DetailInlineEditFieldProps {
  value: string;
  editType: 'year' | 'date';
  onSave: (value: string) => void;
}

/** 详情内联编辑：空值显示「未上传」，编辑图标由字段卡片右侧展示 */
export function DetailInlineEditField({ value, editType, onSave }: DetailInlineEditFieldProps) {
  const [editing, setEditing] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const labelId = useId();
  const yearOptions = useMemo(() => buildYearOptions(), []);

  const display = editType === 'date' ? formatDateYmd(value) || value : value;
  const empty = isEmpty(value);
  const editLabel = editType === 'year' ? '选择出厂年份' : '选择采购入库日期';

  const dismiss = useCallback(() => {
    setEditing(false);
  }, []);

  useDismissOnFocusOutside(editing, wrapRef, dismiss);

  const startEdit = () => {
    setEditing(true);
  };

  const commit = (next: string) => {
    setEditing(false);
    if (!isEmpty(next) && next !== value) onSave(next);
  };

  const editButton = (
    <button
      type="button"
      className={`vm-detail-edit-btn vm-detail-field-action${editing ? ' is-active' : ''}`}
      onClick={startEdit}
      aria-label={editLabel}
      title={editLabel}
      aria-expanded={editing ? true : undefined}
    >
      <Pencil size={14} aria-hidden />
    </button>
  );

  if (editing) {
    const draft = editType === 'date'
      ? (isEmpty(value) ? '' : formatDateYmd(value))
      : (isEmpty(value) ? '' : value);

    return (
      <div className="vm-detail-inline-edit" ref={wrapRef}>
        <span id={labelId} className={empty ? 'vm-detail-inline-empty' : undefined}>
          {empty ? '未上传' : display}
        </span>
        {editButton}
        <div
          className="vm-detail-inline-popover"
          role="dialog"
          aria-label={editLabel}
          onKeyDown={(event) => {
            if (event.key === 'Escape') dismiss();
          }}
        >
          {editType === 'year' ? (
            <SingleYearPickerPanel
              value={draft}
              years={yearOptions}
              onChange={commit}
              onComplete={dismiss}
            />
          ) : (
            <SingleDateCalendarPanel
              value={draft}
              onChange={commit}
              onComplete={dismiss}
            />
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="vm-detail-inline-edit">
      <span id={labelId} className={empty ? 'vm-detail-inline-empty' : undefined}>
        {empty ? '未上传' : display}
      </span>
      {editButton}
    </div>
  );
}
