import React, { useState, useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.css';

// 🔑 Configurable OTP expiry time (in seconds)
const OTP_EXPIRY_SECONDS = 300; // 5 minutes

export default function ResetPassword() {
  const [email, setEmail] = useState('');
  const [otp, setOtp] = useState(['', '', '', '', '', '']); 
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [isOtpExpired, setIsOtpExpired] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const countdownInterval = useRef(null);

  const otpInputRefs = useRef([]);

  // 🔑 Password rules
  const passwordRules = [
    { id: 'length', regex: /.{8,}/, label: 'At least 8 characters' },
    { id: 'uppercase', regex: /[A-Z]/, label: 'One uppercase letter' },
    { id: 'lowercase', regex: /[a-z]/, label: 'One lowercase letter' },
    { id: 'number', regex: /[0-9]/, label: 'One number' },
    { id: 'special', regex: /[^A-Za-z0-9]/, label: 'One special character (e.g., !@#$%)' },
  ];

  const isPasswordValid = (password) => {
    return passwordRules.every(rule => rule.regex.test(password));
  };

  // 🔑 Start countdown timer
  const startCountdown = (seconds) => {
    if (countdownInterval.current) {
      clearInterval(countdownInterval.current);
    }

    setCountdown(seconds);

    countdownInterval.current = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(countdownInterval.current);
          setIsOtpExpired(true);
          localStorage.removeItem('otpData');
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 🔑 On mount: check for existing OTP and resume countdown
  useEffect(() => {
    const stored = localStorage.getItem('otpData');
    if (stored) {
      const { timestamp } = JSON.parse(stored);
      const now = Date.now();
      const elapsedMs = now - timestamp;
      const remainingMs = OTP_EXPIRY_SECONDS * 1000 - elapsedMs;

      if (remainingMs > 0) {
        const remainingSeconds = Math.ceil(remainingMs / 1000);
        startCountdown(remainingSeconds);
      } else {
        localStorage.removeItem('otpData');
        setIsOtpExpired(true);
      }
    }

    // Cleanup on unmount
    return () => {
      if (countdownInterval.current) {
        clearInterval(countdownInterval.current);
      }
    };
  }, []);

  // 🔑 Save OTP with timestamp
  const saveOtpWithTimestamp = (email, otpCode) => {
    localStorage.setItem('otpData', JSON.stringify({
      email,
      otp: otpCode,
      timestamp: Date.now(),
    }));
  };

  // 🔑 Get saved OTP data
  const getSavedOtpData = () => {
    const stored = localStorage.getItem('otpData');
    if (stored) {
      const data = JSON.parse(stored);
      const now = Date.now();
      if (now - data.timestamp <= OTP_EXPIRY_SECONDS * 1000) {
        return data;
      } else {
        localStorage.removeItem('otpData');
        setIsOtpExpired(true);
      }
    }
    return null;
  };

  // Handle OTP input
  const handleOtpChange = (index, value) => {
    if (/^\d?$/.test(value)) {
      const newOtp = [...otp];
      newOtp[index] = value;
      setOtp(newOtp);
      if (value !== '' && index < otp.length - 1) {
        otpInputRefs.current[index + 1]?.focus();
      }
    }
  };

  const handleOtpKeyDown = (index, e) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      otpInputRefs.current[index - 1]?.focus();
    }
  };

  const handleOtpPaste = (e) => {
    e.preventDefault();
    const paste = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);
    if (paste.length === 6) {
      const newOtp = paste.split('');
      setOtp(newOtp);
    }
  };

  // 🔑 Handle "Send OTP" click
  const handleSendOtp = () => {
    if (!email || !/\S+@\S+\.\S+/.test(email)) return;
    
    console.log('Send OTP clicked for:', email);
    alert('✅ Simulated "Send OTP" API call!');
    
    setTimeout(() => {
      const demoOtp = ['1','2','3','4','5','6'];
      setOtp(demoOtp);
      saveOtpWithTimestamp(email, demoOtp.join(''));
      startCountdown(OTP_EXPIRY_SECONDS); // ✅ Start fresh countdown
    }, 1000);
  };

  // 🔑 Handle "Resend OTP" click
  const handleResendOtp = () => {
    if (!email || !/\S+@\S+\.\S+/.test(email)) {
      setError('Please enter a valid email first');
      return;
    }
    
    console.log('Resend OTP clicked for:', email);
    alert('✅ OTP resent!');
    
    setOtp(['', '', '', '', '', '']);
    localStorage.removeItem('otpData');
    setIsOtpExpired(false);
    
    setTimeout(() => {
      const demoOtp = ['6','5','4','3','2','1'];
      setOtp(demoOtp);
      saveOtpWithTimestamp(email, demoOtp.join(''));
      startCountdown(OTP_EXPIRY_SECONDS); // ✅ Start fresh countdown
    }, 1000);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess(false);

    if (!isPasswordValid(newPassword)) {
      setError('Password does not meet security requirements');
      return;
    }

    if (newPassword !== confirmPassword) {
      setError('Passwords do not match');
      return;
    }

    const otpCode = otp.join('');
    if (otpCode.length !== 6) {
      setError('Please enter a 6-digit OTP');
      return;
    }

    const savedOtpData = getSavedOtpData();
    if (!savedOtpData) {
      setError('OTP has expired or was not requested. Please request a new OTP.');
      return;
    }

    if (savedOtpData.otp !== otpCode) {
      setError('Invalid OTP. Please check your code.');
      return;
    }

    if (savedOtpData.email !== email) {
      setError('OTP does not match the email address.');
      return;
    }

    setLoading(true);
    try {
      console.log('API Payload:', { email, otp: otpCode, newPassword, rememberMe });
      alert('✅ Password reset successful!');
      setSuccess(true);
      localStorage.removeItem('otpData');
      if (countdownInterval.current) {
        clearInterval(countdownInterval.current);
      }
    } catch (err) {
      setError(err.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <div
        className="position-absolute top-0 start-0 w-100 h-100"
        style={{
          backgroundImage: 'url(/assets/images/3.png)',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundRepeat: 'no-repeat',
        }}
      ></div>

      <div className="position-relative d-flex align-items-center justify-content-center min-vh-100 p-3">
        <div className="card shadow-sm border-0 rounded-4 p-4 w-100" style={{ maxWidth: '400px' }}>
          <div className="text-center mb-3">
            <h4 className="text-info fw-bold">Lolita</h4>
          </div>

          <form onSubmit={handleSubmit} className="text-start">
            <h5 className="mb-2 text-center">Reset Your Password</h5>
            <p className="text-muted mb-3 small mt-4">Enter your registered Email</p>

            <div className="mb-3">
              <input
                type="email"
                className="form-control"
                style={{ borderColor: '#e0e0e0', backgroundColor: '#f0f8fa' }}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="Enter email"
                required
                disabled={loading}
              />
            </div>

            <div className="d-flex justify-content-end mb-3">
              <button
                type="button"
                className="btn btn-sm"
                style={{
                  backgroundColor: email && /\S+@\S+\.\S+/.test(email) ? '#00b4d8' : '#cccccc',
                  color: 'white',
                  borderColor: email && /\S+@\S+\.\S+/.test(email) ? '#00b4d8' : '#cccccc',
                }}
                disabled={!email || !/\S+@\S+\.\S+/.test(email) || loading}
                onClick={handleSendOtp}
              >
                Send
              </button>
            </div>

            {/* 🔑 LIVE COUNTDOWN - Only shows when active */}
            {countdown > 0 && (
              <div className="text-muted small mb-2 text-center">
                OTP expires in <strong>{countdown}s</strong>
              </div>
            )}

            {isOtpExpired && countdown === 0 && (
              <div className="alert alert-warning small p-2 mb-3">
                ⚠️ Your OTP has expired. Please request a new one.
              </div>
            )}

            <div className="text-muted small mb-3">
              Didn’t receive OTP?{' '}
              <button
                type="button"
                className="btn btn-link p-0"
                style={{ color: '#ff5757', textDecoration: 'none' }}
                disabled={loading}
                onClick={handleResendOtp}
              >
                Resend
              </button>
            </div>

            <div className="mb-3">
              <label className="form-label small">Enter OTP</label>
              <div className="d-flex gap-2 flex-wrap mt-2">
                {otp.map((digit, index) => (
                  <input
                    key={index}
                    ref={(el) => (otpInputRefs.current[index] = el)}
                    type="text"
                    inputMode="numeric"
                    className="form-control text-center"
                    style={{
                      width: '50px',
                      height: '50px',
                      fontSize: '1.2rem',
                      borderColor: '#e0e0e0',
                      backgroundColor: '#f0f8fa',
                    }}
                    value={digit}
                    onChange={(e) => handleOtpChange(index, e.target.value)}
                    onKeyDown={(e) => handleOtpKeyDown(index, e)}
                    onPaste={handleOtpPaste}
                    maxLength={1}
                    required
                    disabled={loading}
                  />
                ))}
              </div>
            </div>

            {/* Password Section */}
            <div className="mb-3">
              <h6 className="fw-medium mb-2">Create Your Password</h6>
              <div className="mb-3">
                <label className="form-label small">New Password</label>
                <input
                  type="password"
                  className="form-control"
                  style={{ borderColor: '#e0e0e0', backgroundColor: '#f0f8fa' }}
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="••••••••"
                  required
                  disabled={loading}
                />
              </div>

              {/* Password Rules - Only show when user types */}
              {newPassword && (
                <div className="small mb-3">
                  {passwordRules.map((rule) => {
                    const isValid = rule.regex.test(newPassword);
                    return (
                      <div key={rule.id} className="d-flex align-items-center mb-1">
                        <span className="me-2" style={{ fontSize: '0.9rem' }}>
                          {isValid ? '✅' : '❌'}
                        </span>
                        <span className={isValid ? 'text-success' : 'text-muted'}>
                          {rule.label}
                        </span>
                      </div>
                    );
                  })}
                </div>
              )}

              <div className="mb-3">
                <label className="form-label small">Retype Password</label>
                <input
                  type="password"
                  className="form-control"
                  style={{ borderColor: '#e0e0e0', backgroundColor: '#f0f8fa' }}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="••••••••"
                  required
                  disabled={loading}
                />
              </div>
            </div>

            <div className="form-check mb-3">
              <input
                type="checkbox"
                className="form-check-input"
                id="rememberMe"
                checked={rememberMe}
                onChange={(e) => setRememberMe(e.target.checked)}
                disabled={loading}
              />
              <label className="form-check-label small" htmlFor="rememberMe">
                Remember password
              </label>
            </div>

            {error && <div className="alert alert-danger small p-2 mb-3">{error}</div>}
            {success && <div className="alert alert-success small p-2 mb-3">Password updated successfully!</div>}

            <button
              type="submit"
              className="btn w-100 py-2 fw-medium"
              style={{
                backgroundColor: '#00b4d8',
                borderColor: '#00b4d8',
                color: 'white',
              }}
              disabled={loading || !isPasswordValid(newPassword) || !confirmPassword}
            >
              {loading ? 'Processing...' : 'Done'}
            </button>

            <div className="text-center mt-3">
              <Link to="/login" className="text-decoration-none small" style={{ color: '#00b4d8' }}>
                ← Back to Login
              </Link>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}