import React, { useEffect, useState } from 'react';
import TestList from './components/TestList';
import TestForm from './components/TestForm';
import { fetchTests, createTest, updateTest, deleteTest } from './api';

function App() {
  const [tests, setTests] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const loadTests = async () => {
    try {
      setLoading(true);
      const data = await fetchTests();
      setTests(data);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadTests();
  }, []);

  const handleCreate = async (newTest) => {
    try {
      const created = await createTest(newTest);
      setTests((prev) => [...prev, created]);
    } catch (e) {
      setError(e.message);
    }
  };

  const handleUpdate = async (id, updates) => {
    try {
      const updated = await updateTest(id, updates);
      setTests((prev) => prev.map((t) => (t.id === id ? updated : t)));
    } catch (e) {
      setError(e.message);
    }
  };

  const handleDelete = async (id) => {
    try {
      await deleteTest(id);
      setTests((prev) => prev.filter((t) => t.id !== id));
    } catch (e) {
      setError(e.message);
    }
  };

  return (
    <div style={{ padding: '2rem' }}>
      <h1>Test Items</h1>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <TestForm onCreate={handleCreate} />
      {loading ? <p>Loading...</p> : <TestList tests={tests} onUpdate={handleUpdate} onDelete={handleDelete} />}
    </div>
  );
}

export default App;
