import React, { useState } from "react";
import { Link } from "react-router-dom";
import { recoverPassword } from "../api/userApi";
import Message from "../components/Message";

const RecoverPasswordPage = () => {
  const [formData, setFormData] = useState({ username: "", newPassword: "" });
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState("");

  const handleChange = (event) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!formData.username || !formData.newPassword) {
      setMessageType("error");
      setMessage("All fields are required");
      return;
    }

    try {
      const data = await recoverPassword(formData);
      setMessageType("success");
      setMessage(data.message);
      setFormData({ username: "", newPassword: "" });
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-secondary p-4 text-primary">
      <form onSubmit={handleSubmit} className="w-full max-w-md rounded-md border border-primary p-6">
        <h1 className="mb-2 text-2xl font-bold">Password Recovery</h1>
        <p className="mb-6 text-sm">Set a new password for an existing username</p>
        <Message message={message} type={messageType} />

        <label className="mb-2 block text-sm font-semibold">Username</label>
        <input
          name="username"
          value={formData.username}
          onChange={handleChange}
          className="mb-4 w-full rounded-md border border-primary bg-secondary p-3 outline-none"
        />

        <label className="mb-2 block text-sm font-semibold">New Password</label>
        <input
          name="newPassword"
          type="password"
          value={formData.newPassword}
          onChange={handleChange}
          className="mb-4 w-full rounded-md border border-primary bg-secondary p-3 outline-none"
        />

        <button className="w-full rounded-md bg-primary px-4 py-3 font-semibold text-secondary">
          Change Password
        </button>

        <Link to="/login" className="mt-4 block text-sm font-semibold">Back to login</Link>
      </form>
    </div>
  );
};

export default RecoverPasswordPage;
