import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [notes, setNotes] = useState([]);
  const [userNotes, setUserNotes] = useState([]);
  const [newNote, setNewNote] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [searchId, setSearchId] = useState('');
  const [userId, setUserId] = useState('');
  const [userCreationSuccess, setUserCreationSuccess] = useState(false);
  const [noteCreationSuccess, setNoteCreationSuccess] = useState(false);

  // Function to fetch all notes
  const fetchNotes = async () => {
    try {
      const response = await fetch('http://hyeumine.com/notesposted.php');
      if (response.ok) {
        const data = await response.json();
        setNotes(data);
      }
    } catch (error) {
      console.error('Error fetching notes:', error);
    }
  };

  // Function to create a new note
  const handleCreateNote = async () => {
    try {
      const response = await fetch('http://hyeumine.com/newnote.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: userId, note: newNote }),
      });
      if (response.ok) {
        const data = await response.json();
        setUserNotes([...userNotes, data]);
        setNewNote('');
        setNoteCreationSuccess(true); // Set note creation success
      } else {
        console.error('Error creating note:', response.status);
      }
    } catch (error) {
      console.error('Error creating note:', error);
    }
  };

  // Function to create a new user
  const handleCreateUser = async () => {
    try {
      const response = await fetch('http://hyeumine.com/newuser.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ firstname: firstName, lastname: lastName }),
      });
      if (response.ok) {
        const userData = await response.json();
        setUserId(userData.id);
        setUserCreationSuccess(true); // Set user creation success
      } else {
        console.error('Error creating user:', response.status);
      }
    } catch (error) {
      console.error('Error creating user:', error);
    }
  };

  // Function to fetch user-specific notes
  const fetchUserNotes = async () => {
    try {
      const response = await fetch(`http://hyeumine.com/mynotes.php?id=${userId}`);
      if (response.ok) {
        const data = await response.json();
        setUserNotes(data);
      } else {
        console.error('Error fetching user-specific notes:', response.status);
      }
    } catch (error) {
      console.error('Error fetching user-specific notes:', error);
    }
  };

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

  useEffect(() => {
    if (userId) {
      fetchUserNotes();
    }
  }, [userId, fetchUserNotes]);

  return (
    <div className="App">
      <header className="App-header">
        <div className="Create-Containers">
          <div className="Create-Container">
            <h2>Create New Note</h2>
            <input
              type="text"
              className="textbox"
              placeholder="Enter Text Here"
              value={newNote}
              onChange={(e) => setNewNote(e.target.value)}
            />
            <button onClick={handleCreateNote} className="button">
              Create Note
            </button>
            {noteCreationSuccess && <p>Note created successfully!</p>}
          </div>

          <div className="Create-User">
            <h2>Create User</h2>
            <h4>Enter First Name</h4>
            <input
              type="text"
              className="input-fname"
              placeholder="First Name"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
            />
            <h4>Enter Last Name</h4>
            <input
              type="text"
              className="input-lname"
              placeholder="Last Name"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
            />
            <button onClick={handleCreateUser} className="button">
              Create User
            </button>
            {userCreationSuccess && <p>User created successfully!</p>}
          </div>
        </div>

        <div className="display-notes-container">
          <h2>Display Notes</h2>
          <p>
            <strong>Search ID:</strong>
            <input
              id="id-search"
              type="text"
              value={searchId}
              onChange={(e) => setSearchId(e.target.value)}
              placeholder="Enter ID"
            />
          </p>
          <ul className="display-notes">
            {searchId
              ? userNotes
                  .filter((note) => note.id === parseInt(searchId))
                  .map((note) => (
                    <li key={note.id}>
                      <strong>ID:</strong> {note.id}
                      <br />
                      {note.note}
                      <br />
                      <small>{new Date(note.timestamp).toLocaleString()}</small>
                    </li>
                  ))
              : notes.map((note) => (
                  <li key={note.id}>
                    <strong>ID:</strong> {note.id}
                    <br />
                    {note.note}
                    <br />
                    <small>{new Date(note.timestamp).toLocaleString()}</small>
                  </li>
                ))}
          </ul>
        </div>
      </header>
    </div>
  );
}

export default App; cant create user or notes