import React, { useState, useEffect } from 'react';
import axios from 'axios';

const OtpForm = ({ onSuccess }) => {
  const [emailOtp, setEmailOtp] = useState('');
  const [whatsappOtp, setWhatsappOtp] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);
  const [timer, setTimer] = useState(60); // 1 minute in seconds

  useEffect(() => {
    if (timer > 0) {
      const interval = setInterval(() => {
        setTimer(prev => prev - 1);
      }, 1000);
      return () => clearInterval(interval);
    }
  }, [timer]);

  const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  const handleOtpChange = (setter) => (e) => {
    const value = e.target.value.replace(/[^0-9]/g, '');
    setter(value);
  };

  const handleResend = async () => {
    setLoading(true);
    setError('');
    setSuccess('');
    try {
      await axios.post('https://api.karyamanswasta.my.id/webhook/otp-request/adventure');
      setSuccess('A new OTP has been sent.');
      setTimer(60); // Reset timer
    } catch (err) {
      setError('Failed to resend OTP.');
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setSuccess('');

    try {
      await axios.post('https://api.karyamanswasta.my.id/webhook/otp-verify/adventure', {
        emailOtp,
        whatsappOtp,
      });
      setSuccess('Account verified successfully! Redirecting to login...');
      setTimeout(() => {
        onSuccess();
      }, 2000);
    } catch (err) {
      setError(err.response?.data?.message || 'OTP verification failed.');
    } finally {
      setLoading(false);
    }
  };

  const isFormValid = emailOtp.length >= 6 && whatsappOtp.length >= 6;

  return (
    <>
      <div className="text-center">
        <h2 className="text-3xl font-bold text-white">Verify Your Account</h2>
        <p className="mt-2 text-sm text-gray-300">Enter the OTP sent to your email and WhatsApp</p>
        <p className="mt-4 text-lg font-medium text-brand-orange">{formatTime(timer)}</p>
      </div>
      <form className="mt-8 space-y-6" onSubmit={handleVerify}>
        <input
          name="emailOtp"
          type="text"
          maxLength="6"
          required
          className="appearance-none relative block w-full px-4 py-3 border border-gray-500 bg-white/20 text-white placeholder-gray-300 focus:outline-none focus:ring-brand-orange focus:border-brand-orange sm:text-sm rounded-md"
          placeholder="Email OTP"
          value={emailOtp}
          onChange={handleOtpChange(setEmailOtp)}
        />
        <input
          name="whatsappOtp"
          type="text"
          maxLength="6"
          required
          className="appearance-none relative block w-full px-4 py-3 border border-gray-500 bg-white/20 text-white placeholder-gray-300 focus:outline-none focus:ring-brand-orange focus:border-brand-orange sm:text-sm rounded-md"
          placeholder="WhatsApp OTP"
          value={whatsappOtp}
          onChange={handleOtpChange(setWhatsappOtp)}
        />
        {error && <p className="text-sm text-red-300 text-center">{error}</p>}
        {success && <p className="text-sm text-green-400 text-center">{success}</p>}
        <div>
          <button
            type="submit"
            disabled={loading || timer === 0 || !isFormValid}
            className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-bold rounded-md text-white bg-brand-orange hover:bg-opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-orange focus:ring-offset-gray-800 disabled:opacity-60"
          >
            {loading ? 'Verifying...' : 'Verify Account'}
          </button>
        </div>
        {timer === 0 && (
          <button
            type="button"
            onClick={handleResend}
            disabled={loading}
            className="w-full text-center text-sm font-medium text-brand-orange hover:underline disabled:opacity-60"
          >
            Resend OTP
          </button>
        )}
      </form>
    </>
  );
};

export default OtpForm;