import { useState } from "react";
import { Input } from "../../Base/Input/Input";
import { Button } from "../../Base/Buttons/Button";
import styles from "./Login.module.css";

export const Login = ({
  loginHeading = "Login With Your Mobile Number",
  placeholder = "Enter Mobile Number",
  onLogin,
}) => {
  const [phoneNumber, setPhoneNumber] = useState("");
  const [error, setError] = useState("");

 const validatePhoneNumber = (number) => {
    const phoneRegex = /^\+?\d{10,15}$/;
    return phoneRegex.test(number);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!phoneNumber.trim()) {
      setError('Phone number is required');
      return;
    }
    if(phoneNumber.length<10){
      setError('phone number contain 10 numbers!!');
      return;
    }
    if (!validatePhoneNumber(phoneNumber)) {
      setError('Please enter only numbers');
      return;
    }

    try {
      await onLogin?.(phoneNumber);
    } catch (err) {
      setError('Login failed. Please try again.');
    }
  };

  const handleInputChange = (e) => {
    setPhoneNumber(e.target.value);
    if (error) {
      setError('');
    }
  };

  return (
    <div className={styles.formcontainer}>
      {/* <div className={styles.leftcontainer}>
        <h1 className={styles.text}>{heading}</h1>
        <p className={styles.content}>{description}</p>
        <button>{buttonLabel}</button>
      </div> */}

        {/* <h2 className={styles.headerNew}>{loginHeading}</h2> */}
        <form className={styles.form} onSubmit={handleSubmit}>
          <div className={styles.input}>
            <Input
              id="phone-number"
              type="tel"
              value={phoneNumber}
              variant="inputbox"
              placeholder={placeholder}
              onChange={handleInputChange}
              isInvalid={!!error}
              errorMessage={error}
            />
          </div>
          <Button variant="primary" label="Login" size="md" />
        </form>
      </div>

  );
};
