import { useState } from 'react';
import { addAppToSection } from '../services/api';
import '../style/AddAppModal.css';
import { IoIosAddCircleOutline } from "react-icons/io";

function AddAppModal({ onAdded }) {
  const [open, setOpen] = useState(false);

  const [section, setSection] = useState('');
  const [name, setName] = useState('');
  const [icon, setIcon] = useState('');
  const [description, setDescription] = useState('');
  const [url, setUrl] = useState('');


  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await addAppToSection({ section, app: { name, icon, description, url } });
      setOpen(false);
      setSection('');
      setName('');
      setIcon('');
      setDescription('');
      setUrl('');
      if (onAdded) onAdded();
    } catch (err) {
      alert('Failed to add app');
    }
  };

  return (
    <>
      <IoIosAddCircleOutline
        className="add-button"
        onClick={() => setOpen(true)}
      />

      {open && (
        <div className="modal-overlay" onClick={() => setOpen(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h2>Add New App</h2>
            <form onSubmit={handleSubmit}>
              <input type="text" placeholder="Section" value={section} onChange={e => setSection(e.target.value)} required />
              <input type="text" placeholder="App name" value={name} onChange={e => setName(e.target.value)} required />
              <input type="text" placeholder="Icon URL" value={icon} onChange={e => setIcon(e.target.value)} />
              <input type="text" placeholder="Description" value={description} onChange={e => setDescription(e.target.value)} />
              <input type="text" placeholder="App URL" value={url} onChange={e => setUrl(e.target.value)} required />
              <button type="submit">Add</button>
            </form>
          </div>
        </div>
      )}
    </>
  );
}

export default AddAppModal;
