import React, { useCallback, useRef, useState } from 'react';
import { Pencil } from 'lucide-react';
import { OperateCityPickerPanel } from './OperateCityPickerPanel';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';
import { operateCitySourceTagClass } from '../utils/vehicle';

interface DetailOperateCityInlineEditProps {
  cityText: string;
  citySource: string | null;
  location: string;
  onSave: (location: string) => void;
}

export function DetailOperateCityInlineEdit({
  cityText,
  citySource,
  location,
  onSave,
}: DetailOperateCityInlineEditProps) {
  const [editing, setEditing] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

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

  useDismissOnFocusOutside(editing, wrapRef, dismiss);

  const handleSelect = (nextLocation: string) => {
    setEditing(false);
    if (nextLocation && nextLocation !== location) {
      onSave(nextLocation);
    }
  };

  return (
    <div className="vm-detail-inline-edit vm-detail-stat-inline-edit" ref={wrapRef}>
      <div className="vm-detail-stat-value vm-detail-stat-value--rich">
        <div className="vm-cell-tags">
          <span>{cityText}</span>
          {citySource ? (
            <span className={operateCitySourceTagClass(citySource)}>{citySource}</span>
          ) : null}
        </div>
      </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--operate-city"
          role="dialog"
          aria-label="修改运营城市"
          onKeyDown={(event) => {
            if (event.key === 'Escape') dismiss();
          }}
        >
          <OperateCityPickerPanel
            location={location}
            onSelect={handleSelect}
            autoFocusSearch
          />
        </div>
      ) : null}
    </div>
  );
}
