import { useState } from 'react';
import { Button } from '@ablogcms/components/button';
import VisuallyHidden from '@ablogcms/components/visually-hidden';
import { AdminCardLaneType } from '../../types';

interface AdminLaneHeaderProps {
  lane: AdminCardLaneType;
  titleStyle?: React.CSSProperties;
  addLane: () => void;
  removeLane: (id: string) => void;
  doneEdit: (lane: AdminCardLaneType) => void;
}

function AdminLaneHeader({ lane, titleStyle, addLane, removeLane, doneEdit }: AdminLaneHeaderProps) {
  const [editMode, setEditMode] = useState(false);
  const [title, setTitle] = useState(lane.title);

  const { id, index, movable, cards } = lane;

  const handleDoneEdit = () => {
    setEditMode(false);
    doneEdit({
      id,
      index,
      title,
      cards,
    });
  };

  return (
    <div>
      {movable !== false && <span className="acms-admin-icon-sort acms-admin-menu-lane-sort" />}
      {index !== 0 && (
        <button
          type="button"
          className="acms-admin-menu-lane-remove-btn"
          onClick={() => {
            removeLane(id);
          }}
          aria-label={ACMS.i18n('admin_menu.remove_lane')}
        >
          ×
        </button>
      )}
      {!editMode && (
        <button
          type="button"
          className="acms-admin-menu-lane-title-toggle"
          style={titleStyle}
          disabled={index === 0}
          onClick={() => setEditMode(true)}
        >
          <span className="acms-admin-menu-lane-title-inner">
            {title}
            {index !== 0 && <span className="acms-admin-icon-control-edit acms-admin-menu-lane-title-edit-icon" />}
          </span>
        </button>
      )}
      {editMode && (
        <label>
          <input
            type="text"
            value={title}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
              setTitle(event.target.value);
            }}
            onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {
              if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
                event.preventDefault();
                handleDoneEdit();
              }
            }}
          />
          <VisuallyHidden>{ACMS.i18n('admin_menu.lane_title')}</VisuallyHidden>
        </label>
      )}
      {index === 0 && (
        <Button variant="success" onClick={addLane} style={{ position: 'absolute', top: '5px', right: '10px' }}>
          {ACMS.i18n('admin_menu.add_lane')}
        </Button>
      )}
      {editMode && (
        <Button className="acms-admin-menu-lane-done-btn" onClick={handleDoneEdit}>
          {ACMS.i18n('admin_menu.complete')}
        </Button>
      )}
    </div>
  );
}

export default AdminLaneHeader;
