"use client";

import React, { useState } from "react";
import axios from "axios";
import { useSearchParams } from "next/navigation";

export default function ResetPasswordForm() {
  const searchParams = useSearchParams();

  // ✅ token and email are read from the URL: /reset-password?email=...&token=...
  const email = searchParams.get("email") || "";
  const token = searchParams.get("token") || "";

  const [newPassword, setNewPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  const handleReset = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage("");
    try {
      await axios.post("http://localhost:3010/api/auth/reset-password", {
        email,
        token,          // ✅ use token from URL
        newPassword,
      });
      setMessage("✅ Your password has been successfully reset.");
    } catch (err) {
      console.error(err);
      setMessage("❌ Reset failed. Check the link or try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleReset} className="space-y-5">
      <div>
        <label className="block text-sm font-medium text-white-dark mb-1">
          New Password
        </label>
        <input
          type="password"
          required
          value={newPassword}
          onChange={(e) => setNewPassword(e.target.value)}
          className="form-input w-full rounded-md border-white-light bg-transparent text-black dark:text-white"
          placeholder="********"
        />
      </div>

      <button
        type="submit"
        disabled={loading}
        className="btn btn-primary w-full uppercase font-bold"
      >
        {loading ? "Resetting..." : "Reset Password"}
      </button>

      {message && (
        <p className="mt-2 text-center text-sm font-semibold text-primary">
          {message}
        </p>
      )}
    </form>
  );
}
