"use client";
import Link from "next/link";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { useSearchParams, useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { resetPassword } from "@/store/slices/authSlice";
import { toast } from "react-toastify";

export default function ResetPasswordForm() {
  const [showPassword, setShowPassword] = useState(false);
  const { register, handleSubmit: handleFormSubmit, formState: { errors } } = useForm();
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const dispatch = useAppDispatch();
  const { isLoading } = useAppSelector((state) => state.auth);
  const router = useRouter();

  const onSubmit = async (data: any) => {
    if (!token) {
      toast.error("Reset token is missing or invalid");
      return;
    }

    try {
      const resultAction = await dispatch(resetPassword({ token, newPassword: data.password }));
      if (resetPassword.fulfilled.match(resultAction)) {
        toast.success("Password reset successful");
        router.push("/login");
      } else {
        toast.error((resultAction.payload as string) || "Failed to reset password");
      }
    } catch (err: any) {
      toast.error(err.message || "An error occurred");
    }
  };

  return (
    <div className="flex flex-col flex-1 w-full lg:w-1/2">
      <div className="w-full max-w-md mx-auto mb-5 sm:pt-10">
      </div>
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          <div className="mb-5 sm:mb-8">
            <h1 className="mb-2 font-semibold text-gray-800 text-title-sm sm:text-title-md">
              Reset Password
            </h1>
            <p className="text-sm text-gray-500">
              Enter your new password to access your account.
            </p>
          </div>
          <div>
            <form onSubmit={handleFormSubmit(onSubmit, (errors) => {
              if (errors.password) toast.error(errors.password.message as string);
              else toast.error("Please fill all required fields");
            })}>
              <div className="space-y-6">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">New Password
                    <span className="text-error-500">*</span>
                  </label>
                  <div className="relative">
                    <input
                      {...register("password", {
                        required: "Password is required",
                        minLength: { value: 6, message: "Password must be at least 6 characters" }
                      })}
                      placeholder="Enter your new password"
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.password ? 'border-error-500' : 'border-gray-300'}`}
                      type={showPassword ? "text" : "password"}
                      disabled={isLoading}
                    />
                    <span
                      className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" className="fill-gray-500">
                        <path fillRule="evenodd" d="M4.638 3.577a.75.75 0 0 0-1.06 1.06l1.275 1.277a8.03 8.03 0 0 0-2.437 3.545.75.75 0 0 0 0 .487 8.02 8.02 0 0 0 11.083 4.614l1.864 1.863a.75.75 0 1 0 1.06-1.06zm7.723 9.844-1.914-1.913q-.212.052-.44.053h-.015a1.858 1.858 0 0 1-1.803-2.312l-2.27-2.27a6.53 6.53 0 0 0-1.996 2.723 6.52 6.52 0 0 0 8.438 3.72m3.716-3.719a6.5 6.5 0 0 1-1.257 2.03l1.061 1.06a8 8 0 0 0 1.704-2.846.75.75 0 0 0 0-.487A8.02 8.02 0 0 0 7.522 4.433l1.23 1.23q.607-.12 1.248-.12a6.52 6.52 0 0 1 6.077 4.16" clipRule="evenodd"></path>
                      </svg>
                    </span>
                  </div>
                  {errors.password && <p className="mt-1 text-xs text-error-500">{errors.password.message as string}</p>}
                </div>
                <div>
                  <button disabled={isLoading} className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition w-full px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-gray-400 disabled:opacity-50">
                    {isLoading ? "Resetting..." : "Reset Password"}
                  </button>
                </div>
                <div className="text-center">
                  <Link href="/login" className="text-sm text-brand-950 hover:text-yellow-500">
                    Back to Log In
                  </Link>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}

