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

import './Register.css';

const PhoneVerification = ({ phoneNumber, onVerify, onResend }) => {
  const [code, setCode] = useState(['', '', '', '', '', '']);
  const [timeLeft, setTimeLeft] = useState(60);
  const [isResending, setIsResending] = useState(false);

  useEffect(() => {
    if (timeLeft > 0) {
      const timer = setTimeout(() => setTimeLeft(timeLeft - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [timeLeft]);

  const handleChange = (index, value) => {
    if (/^\d$/.test(value) || value === '') {
      const newCode = [...code];
      newCode[index] = value;
      setCode(newCode);

      // Auto-focus next input
      if (value && index < 5) {
        document.getElementById(`code-${index + 1}`).focus();
      }

      // Submit if all fields are filled
      if (newCode.every((digit) => digit !== '') && index === 5) {
        handleSubmit(newCode.join(''));
      }
    }
  };

  const handleKeyDown = (index, e) => {
    if (e.key === 'Backspace' && !code[index] && index > 0) {
      document.getElementById(`code-${index - 1}`).focus();
    }
  };

  const handleSubmit = (verificationCode) => {
    onVerify(verificationCode);
  };

  const handleResend = async () => {
    setIsResending(true);
    await onResend();
    setTimeLeft(60);
    setIsResending(false);
  };

  return (
    <div className="verification-container">
      <h3>Verify Your Phone</h3>
      <p>We've sent a 6-digit code to {phoneNumber}</p>

      <div className="code-inputs">
        {code.map((digit, index) => (
          <input
            key={index}
            id={`code-${index}`}
            type="text"
            maxLength="1"
            value={digit}
            onChange={(e) => handleChange(index, e.target.value)}
            onKeyDown={(e) => handleKeyDown(index, e)}
            className="code-input"
          />
        ))}
      </div>

      <button
        onClick={() => handleSubmit(code.join(''))}
        className="verify-btn"
      >
        Verify Code
      </button>

      <div className="resend-section">
        {timeLeft > 0 ? (
          <p>Resend code in {timeLeft}s</p>
        ) : (
          <button
            onClick={handleResend}
            disabled={isResending}
            className="resend-btn"
          >
            {isResending ? 'Sending...' : 'Resend Code'}
          </button>
        )}
      </div>
    </div>
  );
};

export default PhoneVerification;
