import React from 'react';
import {Link,useNavigate  } from 'react-router-dom';
import axios from 'axios';
import { useState,useEffect } from "react";
import { Helmet } from 'react-helmet';

function UserLogin(navigation,props) {
  const navigate = useNavigate();
  const [inputField, setInputField] = useState({phone: '', otp: ''});
  const [isBackButtonClicked, setBackbuttonPress] = useState(false);
  const [otpSent, setOtpSent] = useState(false);
  const [countdown, setCountdown] = useState(0);

  useEffect(() => {
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', onBackButtonEvent);

    window.onbeforeunload = function () {
      return "Data will be lost if you leave the page, are you sure?";
    };

    // Countdown timer
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }

    return () => {
      window.removeEventListener('popstate', onBackButtonEvent);
    }
  }, [countdown]);

  const onBackButtonEvent = (e) => {
    e.preventDefault();
    if (!isBackButtonClicked) {
      if (window.confirm("Do you want to go to Main Website")) {
        setBackbuttonPress(true)
      } 
    }
  }

  const handleChange = (e) => {
    const value = e.target.value;
    setInputField({
      ...inputField,
      [e.target.name]: value
    });
  }

  const handleSendOtp = (e) => {
    e.preventDefault();
    if (!inputField.phone || inputField.phone.length !== 10) {
      alert("Please enter a valid 10-digit phone number");
      return;
    }
    
    // Simulate OTP sending
    setOtpSent(true);
    setCountdown(30); // 30 seconds countdown
    alert(`OTP sent to ${inputField.phone}`);
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!otpSent) {
      alert("Please request OTP first");
      return;
    }
    if (!inputField.otp || inputField.otp.length !== 6) {
      alert("Please enter a valid 6-digit OTP");
      return;
    }
    
    // Simulate login with OTP
    axios.post('https://easycomm.in/rest3/login_api', {phone: inputField.phone, otp: inputField.otp})
      .then((res) => {
        if(res.data.status === 0) {
          localStorage.setItem('token', 1);
          localStorage.setItem('isLoggedIn', true);
          localStorage.setItem('userid', res.data.userid);
          localStorage.setItem('name', res.data.name);
          navigate("/dashboard");
        } else {
          alert(res.data.msg);
        }
      })
      .catch((err) => alert("Could not reach server"));
  }

  return (
    <div className='wrapper' style={{backgroundColor: '#f3e5f5'}}>
      <Helmet>
        <link rel="stylesheet" href="/site/css/style.css"/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/> 
        <script src="/site/js/lib/bootstrap.bundle.min.js"></script>
        <script src="/site/js/plugins/splide/splide.min.js"></script>
        <style>{`
          .btn-primary {
            background-color: #6a1b9a !important;
            border-color: #6a1b9a !important;
            color: white !important;
          }
          .btn-outline-primary {
            border-color: #6a1b9a !important;
            color: #6a1b9a !important;
          }
          .btn-outline-primary:hover {
            background-color: #6a1b9a !important;
            color: white !important;
          }
          .card {
            border-radius: 10px;
            border: 1px solid #d1c4e9;
          }
          h1, h4, .label {
            color: #4a148c !important;
          }
          a {
            color: #6a1b9a !important;
          }
          input {
            color: #212121 !important;
          }
        `}</style>
      </Helmet>
      <div id="appCapsule" style={{maxWidth: '500px', margin: '0 auto'}}>
        <div className="section mt-4 text-center">
          <h1>Log in</h1>
          <h4>Access with your phone number</h4>
        </div>
        
        <div className="section mb-5 p-2">
          <form method='post' onSubmit={handleSubmit}>
            <div className="card">
              <div className="card-body pb-1">
                <div className="form-group basic">
                  <div className="input-wrapper">
                    <label className="label" htmlFor="phone">Phone Number</label>
                    <input 
                      type="tel" 
                      name="phone"  
                      onChange={handleChange} 
                      className="form-control" 
                      required 
                      placeholder="10-digit mobile number"
                      maxLength="10"
                      style={{color: '#000'}}
                    />
                  </div>
                </div>

                {otpSent && (
                  <div className="form-group basic">
                    <div className="input-wrapper">
                      <label className="label" htmlFor="otp">OTP</label>
                      <input 
                        type="text" 
                        name="otp"  
                        onChange={handleChange} 
                        className="form-control" 
                        required 
                        placeholder="6-digit OTP"
                        maxLength="6"
                        style={{color: '#000'}}
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>

            {!otpSent ? (
              <button 
                type="button" 
                onClick={handleSendOtp}
                className="btn btn-primary btn-block btn-lg"
              >
                Send OTP
              </button>
            ) : (
              <>
                <button 
                  type="submit" 
                  className="btn btn-primary btn-block btn-lg"
                >
                  Verify & Login
                </button>
                {countdown > 0 ? (
                  <p className="text-center mt-2" style={{color: '#6a1b9a'}}>
                    Resend OTP in {countdown} seconds
                  </p>
                ) : (
                  <button 
                    type="button" 
                    onClick={handleSendOtp}
                    className="btn btn-outline-primary btn-block btn-sm mt-2"
                  >
                    Resend OTP
                  </button>
                )}
              </>
            )}

            <div className="form-links mt-3">
              <div>
                <Link to="/register">New User? Register Now</Link>
              </div>
            </div>
            
            <hr style={{borderColor: '#d1c4e9'}}/>
            <div className='text-center'>
              <a className='text-center' href='https://capitalsgrowth.in/'>Back to Website</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

export default UserLogin;