import React, { useState } from "react";
import InputField from "./InputField";
import { api } from "../API/API";

function ChangeUsername(): JSX.Element {
  const [newUsername, setNewUsername] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    setNewUsername(e.target.value);
  };

  const handleSubmit = async (): Promise<void> => {
    try {
      // Call the API function to change the username
      const token = localStorage.getItem("accessToken") ?? "";
      const response = await api.changeUserName(
        { prevName: "currentName", newName: newUsername },
        token,
      );
      if (response.success) {
        // Optionally, add a success message or redirect the user
        console.log("Username changed successfully");
      } else {
        // Handle the error message
        console.error("Failed to change username:", response.message);
      }
    } catch (error) {
      console.error("Error changing username:", error);
      // Optionally, handle the error
      setErrorMessage("Failed to change username");
    }
  };

  const handleButtonClick = (): void => {
    handleSubmit().catch((error) => {
      console.error("Error in handleSubmit:", error);
    });
  };

  return (
    <div>
      <InputField
        label="New Username"
        type="text"
        value={newUsername}
        onChange={handleChange}
      />
      {errorMessage && <div>{errorMessage}</div>}
      <button onClick={handleButtonClick}>Update Username</button>
    </div>
  );
}

export default ChangeUsername;
