"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("https://ebay.backend.data4autos.com/api/auth/reset-password", {
        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 mb-1">
          New Password
        </label>
        <input
          type="password"
          required
          value={newPassword}
          onChange={(e) => setNewPassword(e.target.value)}
          className="form-input ps-10 placeholder:text-white-dark"
          placeholder="********"
        />
      </div>

      <button
        type="submit"
        disabled={loading}
        className="btn w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(25,212,251,0.44)] disabled:cursor-not-allowed disabled:opacity-70 !mt-6 bg-[linear-gradient(135deg,#0EA5E9_0%,#19D4FB_50%,#67E8F9_100%)] text-white hover:bg-[linear-gradient(135deg,#67E8F9_0%,#19D4FB_50%,#0EA5E9_100%)]"
      >
        {loading ? "Resetting..." : "Reset Password"}
      </button>

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