'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
import {
  useGetCaptchaQuery,
  useValidateCaptchaMutation
} from '../data/client/user';
import { setCookie } from '../utils';

interface CaptchaViewProps {
  className?: string;
}

export const useCaptcha = () => {
  const { data } = useGetCaptchaQuery();
  const { siteKey, csrfToken } = data ?? {};
  const [validateCaptchaMutation] = useValidateCaptchaMutation();
  const [validated, setValidated] = useState<boolean>(false);
  const [isVisible, setIsVisible] = useState<boolean>(false);
  const [captchaResponse, setCaptchaResponse] = useState<string>(null);

  const validate = async () => {
    if (!captchaResponse) {
      setIsVisible(true);
      return false;
    }

    setValidated(false);

    const response = await validateCaptchaMutation({
      captchaResponse,
      csrfToken
    }).unwrap();

    setValidated(response.success);

    return response.success;
  };

  if (csrfToken) {
    setCookie('csrftoken', csrfToken);
  }

  const onCaptchaChange = useCallback(async (response) => {
    setTimeout(() => {
      setCaptchaResponse(response);
    }, 500);
  }, []);

  useEffect(() => {
    if (captchaResponse) {
      validate();
    }
  }, [captchaResponse]);

  const CaptchaView = useMemo(() => {
    const View = (props: CaptchaViewProps) =>
      isVisible && !captchaResponse ? (
        <ReCAPTCHA
          sitekey={siteKey}
          onChange={onCaptchaChange}
          className={props.className}
        />
      ) : null;

    return View;
  }, [siteKey, onCaptchaChange, isVisible, captchaResponse]);

  return {
    CaptchaView,
    validated,
    isVisible,
    validate
  };
};
