import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Pencil } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { OpsManagerPickerPanel } from './OpsManagerPickerPanel';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';
import { resolveOpsStaffCandidates } from '../utils/vehicle';

interface DetailOpsManagerInlineEditProps {
  record: VehicleRecord;
  managers: string[];
  onSave: (managers: string[]) => void;
}

function sameManagers(a: string[], b: string[]): boolean {
  if (a.length !== b.length) return false;
  const left = [...a].sort();
  const right = [...b].sort();
  return left.every((name, index) => name === right[index]);
}

export function DetailOpsManagerInlineEdit({
  record,
  managers,
  onSave,
}: DetailOpsManagerInlineEditProps) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(managers);
  const draftRef = useRef(managers);
  const wrapRef = useRef<HTMLDivElement>(null);
  const candidates = useMemo(() => resolveOpsStaffCandidates(record), [record]);

  draftRef.current = draft;

  const commitIfChanged = useCallback(() => {
    const next = draftRef.current;
    if (!sameManagers(next, managers)) {
      onSave(next);
    }
  }, [managers, onSave]);

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

  useDismissOnFocusOutside(editing, wrapRef, dismiss);

  useEffect(() => {
    if (!editing) {
      setDraft(managers);
    }
  }, [editing, managers]);

  const display = managers.length ? managers.join('，') : '无';

  return (
    <div className="vm-detail-inline-edit vm-detail-stat-inline-edit" ref={wrapRef}>
      <div className="vm-detail-stat-value">
        <span>{display}</span>
      </div>
      <button
        type="button"
        className={`vm-detail-edit-btn vm-detail-stat-action${editing ? ' is-active' : ''}`}
        onClick={() => setEditing(true)}
        aria-label="修改运维负责人"
        title="修改运维负责人"
        aria-expanded={editing}
      >
        <Pencil size={14} aria-hidden />
      </button>
      {editing ? (
        <div
          className="vm-detail-inline-popover vm-detail-inline-popover--ops"
          role="dialog"
          aria-label="修改运维负责人"
          onKeyDown={(event) => {
            if (event.key === 'Escape') dismiss();
          }}
        >
          <OpsManagerPickerPanel
            value={draft}
            options={candidates}
            onChange={setDraft}
          />
        </div>
      ) : null}
    </div>
  );
}
