import React, { useEffect, useRef, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
import { recaptchaService } from '../../services/api/systemSettingsService';

interface RecaptchaProps {
  onChange?: (token: string | null) => void;
  onError?: (error: string) => void;
  theme?: 'light' | 'dark';
  size?: 'normal' | 'compact';
  className?: string;
}

const Recaptcha: React.FC<RecaptchaProps> = ({
  onChange,
  onError,
  theme = 'dark',
  size = 'normal',
  className = '',
}) => {
  const recaptchaRef = useRef<ReCAPTCHA>(null);
  const [siteKey, setSiteKey] = useState<string>('');
  const [enabled, setEnabled] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await recaptchaService.getRecaptchaSettings();
        if (response.status === 'success' && response.data) {
          setSiteKey(response.data.recaptcha_site_key || '');
          setEnabled(response.data.recaptcha_enabled || false);
        }
      } catch (error) {
        console.error('Error fetching reCAPTCHA settings:', error);
        if (onError) {
          onError('Failed to load reCAPTCHA settings');
        }
      } finally {
        setLoading(false);
      }
    };

    fetchSettings();
  }, [onError]);

  const handleChange = (token: string | null) => {
    if (onChange) {
      onChange(token);
    }
  };

  const handleExpired = () => {
    if (onChange) {
      onChange(null);
    }
  };

  const handleError = () => {
    if (onError) {
      onError('reCAPTCHA error occurred');
    }
    if (onChange) {
      onChange(null);
    }
  };

  if (loading) {
    return null;
  }

  if (!enabled || !siteKey) {
    return null;
  }

  return (
    <div className={className}>
      <ReCAPTCHA
        ref={recaptchaRef}
        sitekey={siteKey}
        onChange={handleChange}
        onExpired={handleExpired}
        onError={handleError}
        theme={theme}
        size={size}
      />
    </div>
  );
};

export default Recaptcha;

