import React, { useState } from "react";
import { Input } from "../../Form/form/Input";
import { Button } from "../../Form/Button/Button";
import { Header } from "../../Layout/Card/Header";
import style from "./Styles.module.css";
import { ToastContainer } from "react-toastify";
import { toast } from "react-toastify";

export const Sign = ({ onClick, onChange, onSwitch }) => {
  const [num, setNum] = useState("");
  const [name, setName] = useState("");

  const Number = (e) => {
    const updated = e.target.value;
    if (onChange) onChange(updated);
    console.log("executed");
    if (/^\d{0,10}$/.test(updated)) {
      setNum(updated);
    }
  };
  const Name = (e) => {
    const User = e.target.value;
    setName(User);
    if (onChange) {
      onChange(e);
    }
  };
  const handleNewUser = () => {
    console.log("signup page worked");
    if (!num || !name) {
      toast.error("Please enter both  Name and Number ");
      return;
    }
    if (!/^[6-9]\d{9}$/.test(num)) {
      toast.info("Please enter a valid 10-digit number");
      return;
    }
    const confirmSignUp = window.confirm("Are you sure you want to Sign Up?");
    if (!confirmSignUp) return;
    console.log("Calling onClick:", { mobile: num, name });
    if (onClick) {
      onClick({ mobile: num, name });
    } else {
      console.log("onclick not defined in sign");
    }
    setName("");
    setNum("");
    if (onSwitch) {
      onSwitch();
    }
  };
  return (
    <>
      <div className={style.container}>
        <div className={style.block}>
          <div className={style.image}>
            <Header title="Sign-Up Page" Color="#000" className={style.head} />
          </div>
          <div className={style.signcontainer}>
            <div className={style.Inpbtn}>
              <Input
                placeholder="Enter Your Mobile Number"
                value={num}
                onChange={Number}
                type="text"
                pattern="[6-9][0-9]{9}"
                min="0"
              />
            </div>
            <div className={style.Inpname}>
              <Input
                placeholder="Enter Your Name"
                value={name}
                onChange={Name}
                type="text"
                maxLength={255}
              />
            </div>
            <div className={style.signbtn}>
              <Button
                children="Submit"
                size="medium"
                primary="true"
                onClick={handleNewUser}
              />
            </div>
          </div>
        </div>
        <ToastContainer />
      </div>
    </>
  );
};
