"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";

export default function AdminChangePasswordPage() {
  const router = useRouter();

  const [currentPassword, setCurrentPassword] =
    useState("");
  const [newPassword, setNewPassword] =
    useState("");
  const [confirmPassword, setConfirmPassword] =
    useState("");

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  async function handleSubmit(
    event: FormEvent<HTMLFormElement>,
  ) {
    event.preventDefault();

    if (loading) return;

    setError("");
    setSuccess("");

    if (newPassword !== confirmPassword) {
      setError("New passwords do not match.");
      return;
    }

    if (
      newPassword.length < 12 ||
      newPassword.length > 72 ||
      !/[A-Z]/.test(newPassword) ||
      !/[a-z]/.test(newPassword) ||
      !/[0-9]/.test(newPassword) ||
      !/[^A-Za-z0-9]/.test(newPassword)
    ) {
      setError(
        "Use 12–72 characters with uppercase, lowercase, number and special character.",
      );
      return;
    }

    if (currentPassword === newPassword) {
      setError(
        "New password must be different from current password.",
      );
      return;
    }

    setLoading(true);

    try {
      const response = await fetch(
        "/api/auth/change-password",
        {
          method: "POST",
          credentials: "same-origin",
          cache: "no-store",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            currentPassword,
            newPassword,
            confirmPassword,
          }),
        },
      );

      const result: {
        passwordChanged?: boolean;
        error?: string;
      } = await response.json();

      if (response.status === 401) {
        setError(
          "Your session has expired. Please sign in again.",
        );
        return;
      }

      if (response.status === 403) {
        setError(
          "You are not authorized to change this password.",
        );
        return;
      }

      if (
        response.status === 400 &&
        result.error === "CURRENT_PASSWORD_INCORRECT"
      ) {
        setError("Current password is incorrect.");
        return;
      }

      if (
        response.status === 400 &&
        result.error === "NEW_PASSWORD_MUST_BE_DIFFERENT"
      ) {
        setError(
          "New password must be different from current password.",
        );
        return;
      }

      if (response.status === 409) {
        setError(
          "Your account was updated elsewhere. Please sign in again.",
        );
        return;
      }

      if (!response.ok || !result.passwordChanged) {
        setError(
          "Unable to change password. Please try again.",
        );
        return;
      }

      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");

      setSuccess(
        "Password changed successfully. Please sign in again.",
      );

      router.replace("/admin/login");
      router.refresh();
    } catch {
      setError(
        "Unable to change password. Please try again.",
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="min-h-[75vh] bg-[var(--soft)] px-5 py-14">
      <div className="mx-auto max-w-lg rounded-2xl border border-slate-200 bg-white p-7 shadow-sm">
        <p className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-blue-700">
          Teja Technology CRM
        </p>

        <h1 className="text-2xl font-bold text-slate-900">
          Change Admin Password
        </h1>

        <p className="mt-3 text-sm text-slate-600">
          Enter your current password and choose a new
          password. After changing it, you must sign in
          again.
        </p>

        <form
          onSubmit={handleSubmit}
          className="mt-7 space-y-5"
        >
          <div>
            <label
              htmlFor="currentPassword"
              className="mb-2 block text-sm font-semibold text-slate-800"
            >
              Current password
            </label>

            <input
              id="currentPassword"
              type="password"
              autoComplete="current-password"
              required
              maxLength={1024}
              value={currentPassword}
              onChange={(event) =>
                setCurrentPassword(event.target.value)
              }
              disabled={loading}
              className="w-full rounded-xl border border-slate-300 px-4 py-3 text-slate-900"
            />
          </div>

          <div>
            <label
              htmlFor="newPassword"
              className="mb-2 block text-sm font-semibold text-slate-800"
            >
              New password
            </label>

            <input
              id="newPassword"
              type="password"
              autoComplete="new-password"
              required
              minLength={12}
              maxLength={72}
              value={newPassword}
              onChange={(event) =>
                setNewPassword(event.target.value)
              }
              disabled={loading}
              className="w-full rounded-xl border border-slate-300 px-4 py-3 text-slate-900"
            />
          </div>

          <div>
            <label
              htmlFor="confirmPassword"
              className="mb-2 block text-sm font-semibold text-slate-800"
            >
              Confirm new password
            </label>

            <input
              id="confirmPassword"
              type="password"
              autoComplete="new-password"
              required
              minLength={12}
              maxLength={72}
              value={confirmPassword}
              onChange={(event) =>
                setConfirmPassword(event.target.value)
              }
              disabled={loading}
              className="w-full rounded-xl border border-slate-300 px-4 py-3 text-slate-900"
            />
          </div>

          {error && (
            <p
              role="alert"
              className="rounded-lg bg-red-50 p-3 text-sm text-red-700"
            >
              {error}
            </p>
          )}

          {success && (
            <p
              role="status"
              className="rounded-lg bg-green-50 p-3 text-sm text-green-700"
            >
              {success}
            </p>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-xl bg-blue-700 px-5 py-3 font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60"
          >
            {loading
              ? "Changing password..."
              : "Change password"}
          </button>
        </form>
      </div>
    </main>
  );
}
