import React, { useState } from 'react';
import styles from './SimpleTable.module.css';
import AutocompleteInput from './AutocompleteInput';

interface Props {
  onClose: () => void;
  onSave: (usuario: { username: string }) => void;
}

const BASE_URL = 'http://localhost:5198/api';

const ModalAnadirUsuario: React.FC<Props> = ({ onClose, onSave }) => {
  const [username, setUsername] = useState('');

  const fetchUserSuggestions = async (query: string): Promise<string[]> => {
    if (!query) return [];
    const response = await fetch(`${BASE_URL}/usuarios/buscar/${query}`);
    if (!response.ok) return [];
    return response.json();
  };

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modal}>
        <h3>Añadir Usuario Manualmente</h3>
        <label>Nombre de Usuario</label>
        <AutocompleteInput
          name="username"
          value={username}
          onChange={e => setUsername(e.target.value)}
          className={styles.modalInput}
          fetchSuggestions={fetchUserSuggestions}
          placeholder="Escribe para buscar o crear un nuevo usuario"
        />
        <div className={styles.modalActions}>
          <button onClick={() => onSave({ username })} className={`${styles.btn} ${styles.btnPrimary}`} disabled={!username.trim()}>Guardar</button>
          <button onClick={onClose} className={`${styles.btn} ${styles.btnSecondary}`}>Cancelar</button>
        </div>
      </div>
    </div>
  );
};

export default ModalAnadirUsuario;