import React, { useState } from 'react';

function TestList({ tests, onUpdate, onDelete }) {
  const [editId, setEditId] = useState(null);
  const [formData, setFormData] = useState({ name: '', description: '' });

  const startEdit = (test) => {
    setEditId(test.id);
    setFormData({ name: test.name, description: test.description || '' });
  };

  const cancelEdit = () => {
    setEditId(null);
    setFormData({ name: '', description: '' });
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const submitUpdate = async (e) => {
    e.preventDefault();
    await onUpdate(editId, formData);
    cancelEdit();
  };

  return (
    <ul>
      {tests.map((test) => (
        <li key={test.id} style={{ marginBottom: '1rem' }}>
          {editId === test.id ? (
            <form onSubmit={submitUpdate}>
              <input
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
                placeholder="Name"
              />
              <input
                name="description"
                value={formData.description}
                onChange={handleChange}
                placeholder="Description"
              />
              <button type="submit">Save</button>
              <button type="button" onClick={cancelEdit}>Cancel</button>
            </form>
          ) : (
            <>
              <strong>{test.name}</strong>: {test.description}
              <button onClick={() => startEdit(test)} style={{ marginLeft: '0.5rem' }}>Edit</button>
              <button onClick={() => onDelete(test.id)} style={{ marginLeft: '0.5rem' }}>Delete</button>
            </>
          )}
        </li>
      ))}
    </ul>
  );
}

export default TestList;
