// components/auth/Captcha.tsx
'use client';

import { useState, useEffect } from 'react';
import { RefreshCcw } from 'lucide-react';
import { getVerificationCaptcha, verifyCaptcha } from '@/lib/api/client';

interface CaptchaProps {
  securityKey: string;
  onVerify: (verified: boolean) => void;
  onError?: (error: string) => void;
}

export function Captcha({ securityKey, onVerify, onError }: CaptchaProps) {
  const [captchaData, setCaptchaData] = useState<{ svg: string }>({ svg: '' });
  const [captchaInput, setCaptchaInput] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);
  const [error, setError] = useState('');
  const [verified, setVerified] = useState(false);

  const fetchCaptcha = async () => {
    try {
      const result = await getVerificationCaptcha(securityKey);
      if (result.success && result.data?.captcha) {
        setCaptchaData({ svg: result.data.captcha });
        setCaptchaInput('');
        setError('');
        setVerified(false);
        onVerify(false);
      } else {
        onError?.(result.message || 'Failed to load CAPTCHA');
      }
    } catch (err) {
      onError?.('Failed to load CAPTCHA');
    }
  };

  useEffect(() => {
    fetchCaptcha();
  }, [securityKey]);

  const handleVerify = async () => {
    if (!captchaInput) {
      setError('Please enter CAPTCHA');
      return;
    }

    setIsVerifying(true);
    try {
      const result = await verifyCaptcha(captchaInput, securityKey);
      if (result.success) {
        setVerified(true);
        setError('');
        onVerify(true);
      } else {
        setError(result.message || 'Invalid CAPTCHA');
        setVerified(false);
        onVerify(false);
        fetchCaptcha();
      }
    } catch (err) {
      setError('Verification failed');
      onVerify(false);
      fetchCaptcha();
    } finally {
      setIsVerifying(false);
    }
  };

  if (verified) {
    return (
      <div className="bg-green-50 border border-green-200 rounded-lg p-3">
        <p className="text-green-700 text-sm">✓ CAPTCHA verified</p>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <label className="text-sm font-medium">Captcha *</label>
      <div className="flex items-center gap-3">
        <div
          className="captcha-wrapper bg-gray-100 p-2 rounded-lg min-w-[120px] flex items-center justify-center"
          dangerouslySetInnerHTML={{ __html: captchaData.svg }}
        />
        <input
          type="text"
          value={captchaInput}
          onChange={(e) => setCaptchaInput(e.target.value)}
          placeholder="Enter result"
          className="flex-1 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
        />
        <button
          type="button"
          onClick={fetchCaptcha}
          className="p-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
        >
          <RefreshCcw size={18} />
        </button>
      </div>
      {error && <p className="text-red-500 text-sm">{error}</p>}
      <button
        type="button"
        onClick={handleVerify}
        disabled={!captchaInput || isVerifying}
        className="w-full py-2 bg-gray-100 rounded-lg text-sm font-medium hover:bg-gray-200 transition-colors disabled:opacity-50"
      >
        {isVerifying ? 'Verifying...' : 'Verify CAPTCHA'}
      </button>
    </div>
  );
}