import React, { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import type { LeaseBusinessDetailRow } from '../types';
import { detailRowYearMonth } from '../utils/detail';
import { DETAIL_EDIT_FIELDS, draftFromRow, parseDraftToPatch } from '../utils/edit-fields';

interface DetailEditModalProps {
  open: boolean;
  row: LeaseBusinessDetailRow | null;
  onClose: () => void;
  onSave: (patch: Partial<LeaseBusinessDetailRow>) => void;
}

export function DetailEditModal({ open, row, onClose, onSave }: DetailEditModalProps) {
  const [draft, setDraft] = useState<Record<string, string | number>>({});

  useEffect(() => {
    if (open && row) setDraft(draftFromRow(row));
  }, [open, row]);

  if (!open || !row) return null;

  const rowLabel = `${detailRowYearMonth(row)} · ${row.plateNo}`;

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    onSave(parseDraftToPatch(draft));
  };

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-modal-lg lbd-edit-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="lbd-edit-title"
        onClick={(event) => event.stopPropagation()}
      >
        <header className="vm-modal-header">
          <h2 id="lbd-edit-title" className="vm-modal-title">编辑明细 · {rowLabel}</h2>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <form id="lbd-edit-form" className="vm-modal-body lbd-edit-form" onSubmit={handleSubmit}>
          <p className="lbd-edit-hint">公式列（应收合计、月度收入、未收、车辆实际成本、总成本、盈亏、氢费等）保存后由系统自动重算。</p>
          <div className="lbd-edit-grid">
            {DETAIL_EDIT_FIELDS.map((field) => (
              <label key={field.key} className="lbd-edit-field">
                <span className="lbd-edit-label">{field.label}</span>
                <input
                  className="vm-input"
                  type={field.type === 'number' ? 'number' : field.type === 'date' ? 'date' : 'text'}
                  step={field.key === 'avgDays' ? '0.01' : field.type === 'number' ? '0.01' : undefined}
                  value={draft[field.key] ?? ''}
                  onChange={(event) => {
                    const value = field.type === 'number'
                      ? event.target.value
                      : event.target.value;
                    setDraft((prev) => ({
                      ...prev,
                      [field.key]: field.type === 'number' && value !== ''
                        ? Number(value)
                        : value,
                    }));
                  }}
                />
              </label>
            ))}
          </div>
        </form>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose} data-vm-icon="x">取消</button>
          <button type="submit" className="vm-btn vm-btn-primary" form="lbd-edit-form" data-vm-icon="save">
            保存
          </button>
        </footer>
      </div>
    </div>
  );
}
