import { useState, useEffect } from "react";

import PersonList from "./components/PersonList";

import personService from "./services/personService";

const SearchArea = ({ onChangeHandler }) => {
  return (
    <div>
      search name: <input onChange={onChangeHandler} />
    </div>
  );
};

const AddPersonForm = ({
  onSubmitHandler,
  onNameChangeHandler,
  nameValue,
  onNumberChangeHandler,
  numberValue,
}) => {
  return (
    <>
      <form onSubmit={onSubmitHandler}>
        <div>
          name: <input value={nameValue} onChange={onNameChangeHandler} />
        </div>
        <div>
          number: <input value={numberValue} onChange={onNumberChangeHandler} />
        </div>
        <div>
          <button type="submit">add</button>
        </div>
      </form>
    </>
  );
};

const App = () => {
  const [persons, setPersons] = useState([]);
  const [searchString, setSearchString] = useState("");
  const [newName, setNewName] = useState("");
  const [newNumber, setNewNumber] = useState("");

  useEffect(() => {
    personService.getPersons().then((response) => {
      console.log(response.data);
      setPersons(response.data);
    });
  }, []);

  const handleOnSubmit = (event) => {
    event.preventDefault();
    if (
      persons.some((person) => {
        return person.name === newName;
      })
    ) {
      alert(`${newName} is already in the phonebook.`);
      return;
    }

    personService
      .addPerson({
        name: newName,
        number: newNumber,
        id: newName,
      })
      .then((response) => {
        setPersons(persons.concat(response.data));
      });
    setNewName("");
    setNewNumber("");
  };

  const handleNameChange = (event) => {
    setNewName(event.target.value);
  };

  const handleNumberChange = (event) => {
    setNewNumber(event.target.value);
  };

  const handleSearchChange = (event) => {
    setSearchString(event.target.value);
  };

  const handlePersonDeletionFactory = ({ person }) => {
    return (event) => {
      personService
        .deletePerson(person.id)
        .then(() => {
          setTimeout(() => {
            console.log("postimeout");
          }, 3000);
        })
        .then(() => {
          return personService.getPersons();
        })
        .then((response) => {
          setPersons(response.data);
        });
    };
  };

  return (
    <div>
      <h2>Phonebook</h2>
      <SearchArea onChangeHandler={handleSearchChange} />
      <h3>Add new</h3>
      <AddPersonForm
        onSubmitHandler={handleOnSubmit}
        onNameChangeHandler={handleNameChange}
        nameValue={newName}
        onNumberChangeHandler={handleNumberChange}
        numberValue={newNumber}
      />
      <h3>Numbers</h3>
      <PersonList
        persons={persons.filter((person) =>
          person.name.toUpperCase().includes(searchString.toUpperCase())
        )}
        deletionHandlerFactory={handlePersonDeletionFactory}
      />
    </div>
  );
};

export default App;
