"use client";

import { useState } from "react";
import { FiLock, FiEye, FiEyeOff } from "react-icons/fi";

import Button from "../../ui/Button";
import Input from "../../ui/CustomInput";
import { useModal } from "../../../lib/modal-system/ModalContext";
import useResetPassword from "../../../hooks/features/auth/reset-password/useResetPassword";
import { useAppForm } from "../../../hooks/useAppForm";
import {
  resetPasswordSchema,
  ResetPasswordSchema,
} from "../../../hooks/features/auth/reset-password/schema";
import { useRouter, useSearchParams } from "next/navigation";
import { MODAL_TYPES } from "../../../lib/modal-system/ModalRegistery";

interface ResetPasswordFormProps {
  token?: string;
}

export default function ResetPasswordForm({
  token: tokenProp,
}: ResetPasswordFormProps) {
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

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

  const router = useRouter();
  const { openModal } = useModal();

  const { handleResetPassword, loading } = useResetPassword();
  const { register, errors, handleSubmit, reset } =
    useAppForm<ResetPasswordSchema>({
      defaultValues: {
        newPassword: "",
        confirmPassword: "",
      },
      schema: resetPasswordSchema,
      onSubmit: async (data) => {
        try {
          await handleResetPassword({ ...data, token: token ?? "" });
          reset();

          openModal("PASSWORD_UPDATED", {});
        } catch (error) {}
      },
    });

  if (!token) {
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.delete("token");
    urlParams.delete("modal");
    urlParams.delete("status");
    const newSearch = urlParams.toString();

    window.history.replaceState(
      {},
      "",
      newSearch ? `?${newSearch}` : window.location.pathname,
    );
    return;
  }

  return (
    <>
      <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-[#E5D8FF] text-link-1 md:h-16 md:w-16">
        <FiLock size={24} />
      </div>

      <h2 className="mt-5 text-center font-heading text-xl md:text-2xl font-semibold text-heading">
        Set New Password
      </h2>
      <div className="mt-7 space-y-3 2xl:space-y-5">
        {/* New Password */}
        <div>
          {/* <label className="mb-2 block font-body text-sm font-medium text-heading">
            New Password
            <span className="text-danger">*</span>
          </label> */}

          <div className="relative">
            <Input
              label="New Password"
              required
              register={register("newPassword")}
              error={errors.newPassword?.message}
              icon={<FiLock />}
              type={showPassword ? "text" : "password"}
              placeholder="Enter Your Password"
              rightIcon={
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="text-link-1 transition hover:opacity-80 cursor-pointer"
                  aria-label={showPassword ? "Hide password" : "Show password"}
                >
                  {showPassword ? <FiEyeOff size={18} /> : <FiEye size={18} />}
                </button>
              }
            />
          </div>
        </div>

        {/* Confirm Password */}
        <div>
          {/* <label className="mb-2 block font-body text-sm font-medium text-heading">
            Confirm Password
            <span className="text-danger">*</span>
          </label> */}

          <div className="relative">
            <Input
              label="Confirm Password"
              register={register("confirmPassword")}
              required
              error={errors.confirmPassword?.message}
              icon={<FiLock />}
              type={showConfirmPassword ? "text" : "password"}
              placeholder="Confirm Your Password"
              rightIcon={
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="text-link-1 transition hover:opacity-80 cursor-pointer"
                  aria-label={
                    showConfirmPassword ? "Hide password" : "Show password"
                  }
                >
                  {showConfirmPassword ? (
                    <FiEyeOff size={18} />
                  ) : (
                    <FiEye size={18} />
                  )}
                </button>
              }
            />
          </div>
        </div>
      </div>

      <Button
        loading={loading}
        className="mt-7.5 w-full"
        onClick={handleSubmit}
      >
        Update Password
      </Button>

      <div className="mt-6 text-center">
        <button
          type="button"
          onClick={() => {
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.delete("token");
            urlParams.delete("modal");
            urlParams.delete("status");
            const newSearch = urlParams.toString();

            window.history.replaceState(
              {},
              "",
              newSearch ? `?${newSearch}` : window.location.pathname,
            );

            openModal(MODAL_TYPES.LOGIN, {});
          }}
          className="font-body text-sm font-medium text-link-1 cursor-pointer"
        >
          Back to Login
        </button>
      </div>
    </>
  );
}
