"use client";

import { useState, useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { resetPassword, clearError } from "@/store/slices/authSlice";
import { AuthField } from "./AuthField";
import { useTranslation } from "@/i18n";
import { ArrowLeft, CheckCircle } from "lucide-react";
import Link from "next/link";

const schema = z
  .object({
    password: z.string().min(6, "Password must be at least 6 characters"),
    password_confirmation: z.string(),
  })
  .refine((d) => d.password === d.password_confirmation, {
    message: "Passwords do not match",
    path: ["password_confirmation"],
  });
type FormValues = z.infer<typeof schema>;

export function ResetPasswordPage() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const searchParams = useSearchParams();
  const { isLoading, error } = useAppSelector((s) => s.auth);
  const { t } = useTranslation();
  const [success, setSuccess] = useState(false);

  const token = searchParams?.get("token") ?? "";

  useEffect(() => {
    if (!token) router.replace("/auth/forgot-password");
  }, [token, router]);

  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
    resolver: zodResolver(schema),
  });

  const onSubmit = async (data: FormValues) => {
    dispatch(clearError());
    const res = await dispatch(
      resetPassword({ token, password: data.password, password_confirmation: data.password_confirmation }),
    );
    if (resetPassword.fulfilled.match(res)) {
      setSuccess(true);
    }
  };

  return (
    <div
      className="rounded-2xl p-8"
      style={{
        background: "var(--auth-card-bg)",
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        border: "1px solid var(--border)",
        boxShadow: "var(--auth-card-shadow)",
      }}
    >
      <Link
        href="/auth/login"
        className="inline-flex items-center gap-2 text-xs font-medium mb-6 transition-opacity hover:opacity-80"
        style={{ color: "var(--text-muted)" }}
      >
        <ArrowLeft size={14} /> {t("auth_backToLogin")}
      </Link>

      {success ? (
        <div className="flex flex-col items-center gap-5 py-4">
          <div
            className="w-16 h-16 rounded-full flex items-center justify-center"
            style={{ background: "rgba(34,197,94,0.12)" }}
          >
            <CheckCircle size={32} className="text-green-400" />
          </div>
          <div className="text-center">
            <h2 className="text-xl font-black mb-2" style={{ color: "var(--text-primary)" }}>{t("auth_resetSuccess")}</h2>
            <p className="text-sm" style={{ color: "var(--text-muted)" }}>
              {t("auth_signInWithNewPassword")}
            </p>
          </div>
          <Link
            href="/auth/login"
            className="px-6 py-2.5 rounded-xl text-sm font-bold text-[#ffffff] transition-all duration-150 active:scale-[0.98]"
            style={{ background: "var(--accent)" }}
          >
            {t("auth_loginLink")}
          </Link>
        </div>
      ) : (
        <>
          <h1 className="text-2xl font-black tracking-tight mb-1" style={{ color: "var(--text-primary)" }}>
            {t("auth_resetTitle")}
          </h1>
          <p className="text-sm mb-7" style={{ color: "var(--text-muted)" }}>
            {t("auth_resetSubtext")}
          </p>

          <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
            <AuthField
              label={t("auth_passwordLabel")}
              isPassword
              placeholder="••••••••"
              error={errors.password?.message}
              autoComplete="new-password"
              {...register("password")}
            />
            <AuthField
              label={t("auth_confirmPasswordLabel")}
              isPassword
              placeholder="••••••••"
              error={errors.password_confirmation?.message}
              autoComplete="new-password"
              {...register("password_confirmation")}
            />

            {error && (
              <p className="text-xs px-3 py-2 rounded-lg" style={{ background: "rgba(239,68,68,0.1)", color: "#ef4444" }}>
                {error}
              </p>
            )}

            <button
              type="submit"
              disabled={isLoading}
              className="w-full py-3 rounded-xl text-sm font-bold tracking-wide text-[#ffffff] transition-all duration-150 active:scale-[0.98] disabled:opacity-60 mt-1"
              style={{ background: "var(--accent)" }}
            >
              {isLoading ? t("auth_resetting") : t("auth_resetButton")}
            </button>
          </form>
        </>
      )}
    </div>
  );
}
