import React, { useId, useRef, useState } from 'react';
import { Pencil } from 'lucide-react';
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 inputRef = useRef<HTMLInputElement | HTMLSelectElement>(null);
  const labelId = useId();

  const display = editType === 'date' ? formatDateYmd(value) || value : value;
  const empty = isEmpty(value);

  const startEdit = () => {
    setEditing(true);
    window.setTimeout(() => inputRef.current?.focus(), 0);
  };

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

  if (editing) {
    if (editType === 'year') {
      return (
        <select
          ref={inputRef as React.RefObject<HTMLSelectElement>}
          className="vm-detail-inline-input"
          defaultValue={isEmpty(value) ? '' : value}
          aria-labelledby={labelId}
          onChange={(e) => commit(e.target.value)}
          onBlur={() => setEditing(false)}
        >
          <option value="">请选择年份</option>
          {buildYearOptions().map((y) => (
            <option key={y} value={y}>{y}</option>
          ))}
        </select>
      );
    }
    return (
      <input
        ref={inputRef as React.RefObject<HTMLInputElement>}
        type="date"
        className="vm-detail-inline-input"
        defaultValue={isEmpty(value) ? '' : formatDateYmd(value)}
        aria-labelledby={labelId}
        onChange={(e) => commit(e.target.value)}
        onBlur={() => setEditing(false)}
      />
    );
  }

  if (empty) {
    return (
      <>
        <span id={labelId}>未上传</span>
        <button
          type="button"
          className="vm-detail-edit-btn vm-detail-field-action"
          onClick={startEdit}
          aria-label={editType === 'year' ? '选择出厂年份' : '选择采购入库日期'}
          title={editType === 'year' ? '选择出厂年份' : '选择采购入库日期'}
        >
          <Pencil size={14} aria-hidden />
        </button>
      </>
    );
  }

  return <span>{display}</span>;
}
