"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "react-toastify";

const COPY_FEEDBACK_TIMEOUT_MS = 2000;

export const useResetPasswordModalPresenter = ({
  isOpen,
  password,
}: {
  isOpen: boolean;
  password: string | null;
}) => {
  const [isCopied, setIsCopied] = useState(false);
  const [isPasswordVisible, setIsPasswordVisible] = useState(false);

  useEffect(() => {
    if (!isOpen) {
      setIsCopied(false);
      setIsPasswordVisible(false);
    }
  }, [isOpen]);

  const togglePasswordVisibility = useCallback(() => {
    setIsPasswordVisible((prev) => !prev);
  }, []);

  const copyPasswordToClipboard = useCallback(async () => {
    if (!password) return;
    try {
      await navigator.clipboard.writeText(password);
      setIsCopied(true);
      toast.success("Password copied to clipboard");
      setTimeout(() => setIsCopied(false), COPY_FEEDBACK_TIMEOUT_MS);
    } catch {
      toast.error("Failed to copy password");
    }
  }, [password]);

  return {
    isCopied,
    isPasswordVisible,
    togglePasswordVisibility,
    copyPasswordToClipboard,
  };
};
