import axios from "axios";
import { useEffect, useState } from "react";
import "./App.css";
const BASE_URL = "http://localhost:3001";
function App() {
  const [quotations, setQuotations] = useState([]);
  const [quotationForm, setQuotationForm] = useState({
    name: "",
    quotation: "",
  });

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

  /**
   * @description get all quotations using api call
   */
  const getQuotationHandler = async () => {
    const res = await axios.get(`${BASE_URL}/quotations`);
    setQuotations([...res.data.data.quotations]);
  };

  /**
   * @description create new quotation and clear form object
   * @param {*} e
   */
  const createQuotationHandler = async (e) => {
    e.preventDefault();
    const res = await axios.post(`${BASE_URL}/quotation`, quotationForm);
    setQuotationForm({
      name: "",
      quotation: "",
    });
    setQuotations((q) => [...q, res.data.data.quotation]);
  };
  return (
    <div className="App">
      <div className="mt-2">
        <h1>Create Quotation</h1>
        <form className="mt-2" onSubmit={createQuotationHandler}>
          <div className="row">
            <div className="col">
              <input
                type="text"
                className="form-control"
                placeholder="Jhon doe"
                required
                onChange={(e) =>
                  setQuotationForm({ ...quotationForm, name: e.target.value })
                }
                value={quotationForm.name}
              />
            </div>
            <div className="col">
              <input
                type="text"
                className="form-control"
                placeholder="quotation..."
                required
                onChange={(e) =>
                  setQuotationForm({
                    ...quotationForm,
                    quotation: e.target.value,
                  })
                }
                value={quotationForm.quotation}
              />
            </div>
            <button type="submit" className="btn btn-primary w-25">
              Create
            </button>
          </div>
        </form>
      </div>
      <div className="mt-5">
        <h1>Create List</h1>
        <table className="table">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Quotation</th>
            </tr>
          </thead>
          <tbody>
            {quotations.map((quotation, index) => (
              <tr key={quotation._id}>
                <th scope="row">{index + 1}</th>
                <td>{quotation.name}</td>
                <td>{quotation.quotation}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default App;
