"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Lock, Eye, EyeOff, CheckCircle2, AlertTriangle, ArrowLeft } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "@/lib/hooks/use-translation";
import { zMsg } from "@/lib/utils/translated-zod";
import { authApi } from "@/lib/api/client";

// Kept in step with app.password-reset.min-password-length on the server, which
// rejects anything shorter regardless of what this form allows through.
const MIN_PASSWORD = 8;

const schema = z
  .object({
    newPassword: z
      .string()
      .min(MIN_PASSWORD, zMsg("auth.password_min_8", "Password must be at least 8 characters")),
    confirmPassword: z.string(),
  })
  .refine((v) => v.newPassword === v.confirmPassword, {
    message: zMsg("auth.passwords_differ", "The two passwords do not match"),
    path: ["confirmPassword"],
  });
type Values = z.infer<typeof schema>;

function ResetForm() {
  const router = useRouter();
  const token = useSearchParams().get("token") ?? "";

  const [done, setDone] = useState(false);
  const [loading, setLoading] = useState(false);
  const [show, setShow] = useState(false);
  const { t: cms } = useTranslation("LOGIN");

  const form = useForm<Values>({ resolver: zodResolver(schema) });

  async function onSubmit(values: Values) {
    try {
      setLoading(true);
      await authApi.resetPassword({ token, newPassword: values.newPassword });
      setDone(true);
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
        "Could not reset the password";
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  }

  const inputCls =
    "w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm placeholder:text-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500";
  const btnPrimary =
    "w-full rounded-md bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition";

  // A link opened without a token — usually a mail client that mangled the URL.
  // Saying so is more useful than a form that will always fail on submit.
  if (!token) {
    return (
      <div className="text-center py-4">
        <AlertTriangle className="h-12 w-12 text-amber-500 mx-auto mb-4" />
        <p className="text-sm text-gray-700 mb-2">
          {cms("reset.no_token_hi", "यह लिंक अधूरा है।")}
        </p>
        <p className="text-sm text-gray-500 mb-6">
          {cms(
            "reset.no_token_en",
            "This link is incomplete. Please request a new one."
          )}
        </p>
        <Link href="/auth/forgot" className="text-sm text-indigo-600 hover:underline">
          {cms("reset.request_new", "नया लिंक मांगें / Request a new link")}
        </Link>
      </div>
    );
  }

  if (done) {
    return (
      <div className="text-center py-4">
        <CheckCircle2 className="h-12 w-12 text-green-600 mx-auto mb-4" />
        <p className="text-sm text-gray-700 mb-2">
          {cms("reset.done_hi", "पासवर्ड बदल दिया गया है।")}
        </p>
        <p className="text-sm text-gray-500 mb-6">
          {cms("reset.done_en", "Your password has been changed. You can sign in now.")}
        </p>
        <button onClick={() => router.push("/auth")} className={btnPrimary}>
          {cms("reset.go_to_login", "लॉगिन करें / Sign in")}
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          <Lock className="inline h-4 w-4 mr-1" />
          {cms("reset.new_password", "नया पासवर्ड / New password")}
        </label>
        <div className="relative">
          <input
            type={show ? "text" : "password"}
            className={inputCls}
            placeholder="••••••••"
            autoFocus
            {...form.register("newPassword")}
          />
          <button
            type="button"
            onClick={() => setShow(!show)}
            className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
          >
            {show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
          </button>
        </div>
        {form.formState.errors.newPassword && (
          <p className="text-xs text-red-500 mt-1">
            {form.formState.errors.newPassword.message}
          </p>
        )}
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          <Lock className="inline h-4 w-4 mr-1" />
          {cms("reset.confirm_password", "पासवर्ड दोहराएं / Confirm password")}
        </label>
        <input
          type={show ? "text" : "password"}
          className={inputCls}
          placeholder="••••••••"
          {...form.register("confirmPassword")}
        />
        {form.formState.errors.confirmPassword && (
          <p className="text-xs text-red-500 mt-1">
            {form.formState.errors.confirmPassword.message}
          </p>
        )}
      </div>

      <button type="submit" disabled={loading} className={btnPrimary}>
        {loading
          ? cms("auth_labels.loading_text", "कृपया प्रतीक्षा करें...")
          : cms("reset.submit", "पासवर्ड बदलें / Change password")}
      </button>
    </form>
  );
}

export default function ResetPasswordPage() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100 px-4 py-12">
      <div className="w-full max-w-md bg-white rounded-xl shadow-lg p-8">
        <h1 className="text-xl font-bold text-center text-gray-900 mb-6">
          नया पासवर्ड सेट करें / Set a new password
        </h1>
        {/* useSearchParams needs a Suspense boundary or the whole route opts out
            of static rendering at build time. */}
        <Suspense fallback={<p className="text-center text-sm text-gray-400">…</p>}>
          <ResetForm />
        </Suspense>
        <Link
          href="/"
          className="mt-6 flex items-center justify-center gap-1 text-sm text-gray-500 transition-colors hover:text-indigo-600"
        >
          <ArrowLeft className="h-4 w-4" />
          होम पर वापस जाएँ / Back to home
        </Link>
      </div>
    </div>
  );
}
