"use client";
import React, { useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { useRouter } from "next/navigation";
import { KeyRound } from "lucide-react";

export default function ResetPasswordPage() {
  const { token } = useAuth();
  const router = useRouter();
  const [current, setCurrent] = useState("");
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [status, setStatus] = useState<string | null>(null);
  const [error, setError] = useDismissingState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const canSubmit = useMemo(() => current.length > 0 && password.length >= 8 && password === confirm, [current, password, confirm]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setStatus(null);
    setError(null);
    if (!token) {
      setError("You must be logged in to change your password.");
      return;
    }
    if (!canSubmit) return;
    try {
      setLoading(true);
      await apiFetch("/api/users/profile", { method: "PUT", authToken: token, body: { password, currentPassword: current } });
      setStatus("Your password has been updated successfully.");
      setCurrent("");
      setPassword("");
      setConfirm("");
      setTimeout(() => router.push("/dashboard/user"), 1200);
    } catch (err: any) {
      setError(err?.message || "Failed to update password");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto w-full p-6">
      <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
            <KeyRound className="w-5 h-5 text-brand-600" />
          </div>
          <h1 className="text-2xl font-semibold text-gray-900">Reset password</h1>
        </div>
        <button
          className="px-2.5 py-1 text-xs rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-1"
          onClick={() => router.push("/dashboard/user")}
        >Back to dashboard</button>
      </div>

      {error && <p className="text-red-600 text-sm mb-3">{error}</p>}
      {status && <p className="text-green-700 text-sm mb-3">{status}</p>}

      <div className="border rounded-xl p-5 bg-white shadow-sm">
        <form onSubmit={submit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">Current password</label>
            <input
              type="password"
              value={current}
              onChange={e => setCurrent(e.target.value)}
              required
              className="w-full border rounded px-3 py-2"
              placeholder="Enter your current password"
            />
            <p className="text-xs text-gray-500 mt-1">For your security, please confirm your current password.</p>
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">New password</label>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              required
              className="w-full border rounded px-3 py-2"
              placeholder="At least 8 characters"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Confirm new password</label>
            <input
              type="password"
              value={confirm}
              onChange={e => setConfirm(e.target.value)}
              required
              className="w-full border rounded px-3 py-2"
            />
            {password && confirm && password !== confirm && (
              <p className="text-xs text-red-600 mt-1">Passwords do not match.</p>
            )}
          </div>
          <div className="flex items-center gap-2">
            <button
              type="submit"
              disabled={!canSubmit || loading}
              className="px-4 py-2 rounded bg-brand-600 hover:bg-brand-700 text-white disabled:opacity-60"
            >{loading ? "Saving…" : "Update password"}</button>
            <button
              type="button"
              className="px-3 py-2 rounded bg-gray-100 hover:bg-gray-200 text-gray-800"
              onClick={() => router.push("/dashboard/user")}
            >Cancel</button>
          </div>
        </form>
      </div>
    </div>
  );
}
