"use client";

import * as React from "react";
import Image from "next/image";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { KeyRound, Lock, ArrowRight, CheckCircle2, ShieldAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { FloatingInput } from "@/components/ui/floating-input";

export default function AdminResetPasswordPage() {
  return (
    <React.Suspense
      fallback={
        <div className="text-center py-12 text-xs text-neutral-400">
          Loading password recovery form...
        </div>
      }
    >
      <ResetPasswordForm />
    </React.Suspense>
  );
}

function ResetPasswordForm() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const token = searchParams.get("token") || "";

  const [newPassword, setNewPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [success, setSuccess] = React.useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!token) {
      setError("Reset token is missing or invalid. Please request a new reset link.");
      return;
    }

    if (newPassword.length < 8) {
      setError("Password must be at least 8 characters long.");
      return;
    }

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

    try {
      setLoading(true);
      const res = await fetch("/api/admin/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, newPassword, confirmPassword }),
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Failed to reset password.");
        return;
      }

      setSuccess(true);
    } catch {
      setError("Network error resetting password. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full max-w-md">
      <div className="rounded-3xl border border-neutral-200 bg-white p-8 shadow-xl dark:border-neutral-800 dark:bg-neutral-900">
        <div className="flex flex-col items-center text-center">
          <div className="relative mb-4 flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl bg-neutral-100 dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700">
            <Image
              src="/images/quto-logo.webp"
              alt="Quto AI"
              width={44}
              height={44}
              className="object-contain"
              priority
            />
          </div>

          <h1 className="text-xl font-bold tracking-tight text-neutral-900 dark:text-white">
            Reset Password
          </h1>
          <p className="mt-1 text-xs text-neutral-500 max-w-xs">
            Create a secure, permanent password for your administrator account.
          </p>
        </div>

        {error && (
          <div className="mt-5 rounded-xl border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700 dark:border-rose-900/50 dark:bg-rose-950/50 dark:text-rose-300 flex items-center gap-2">
            <ShieldAlert className="h-4 w-4 shrink-0 text-rose-500" />
            <span>{error}</span>
          </div>
        )}

        {success ? (
          <div className="mt-6 text-center space-y-4">
            <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-950/60 text-emerald-600">
              <CheckCircle2 className="h-6 w-6" />
            </div>
            <p className="text-xs text-neutral-600 dark:text-neutral-400">
              Your password has been reset successfully. All previous active sessions have been securely terminated.
            </p>
            <Button
              onClick={() => router.push("/admin/login")}
              className="w-full h-11 bg-neutral-900 text-white dark:bg-white dark:text-neutral-900 hover:bg-neutral-800"
            >
              Sign In to Admin Panel
            </Button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="mt-6 space-y-4">
            <FloatingInput
              id="reset-new-password"
              type="password"
              showPasswordToggle
              required
              minLength={8}
              autoComplete="new-password"
              name="new-password"
              label="New Permanent Password (min 8 chars)"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
            />

            <FloatingInput
              id="reset-confirm-password"
              type="password"
              showPasswordToggle
              required
              minLength={8}
              autoComplete="new-password"
              name="confirm-password"
              label="Confirm Permanent Password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
            />

            <Button
              type="submit"
              disabled={loading}
              loading={loading}
              className="w-full h-11 text-xs font-semibold"
            >
              {loading ? "Updating Password..." : "Update Password & Sign In"}
            </Button>

            <div className="text-center pt-2">
              <Link
                href="/admin/login"
                className="text-xs text-neutral-500 hover:text-neutral-900 dark:hover:text-white transition-colors"
              >
                Back to Sign In
              </Link>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
