import { useEffect, useState } from "react";
import api from "../utils/api";

interface FormInput {
  project: string;
  time: string;
  date: string;
}
const CreateLog = ({ authorized }: { authorized: boolean }) => {
  const [params, setParams] = useState<FormInput>({
    project: "",
    time: "",
    date: "",
  });
  const [token, setToken] = useState<String>("");
  useEffect(() => {
    let tmp = localStorage.getItem("token");
    if (tmp !== null) setToken(tmp);
  });
  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (token !== null) {
      const resp = await api.post(
        "/createlog",
        {
          project: params.project,
          time: params.time,
          date: params.date,
        },
        {
          headers: {
            token: token.toString(),
          },
        },
      );
      console.log(resp);
    }
  };
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setParams({ ...params, [e.target.name]: e.target.value });
  };
  if (authorized)
    return (
      <>
        <form onSubmit={onSubmit}>
          <label>Project:</label>
          <input
            type="text"
            name="project"
            value={params.project}
            onChange={onChange}
          />
          <label>Time:</label>
          <input
            type="text"
            name="time"
            value={params.time}
            onChange={onChange}
          />
          <label>Date:</label>
          <input
            type="text"
            name="date"
            value={params.date}
            onChange={onChange}
          />
          <button type="submit">Create Log</button>
        </form>
      </>
    );
  else return <>You are not Logged In</>;
};

export default CreateLog;
