import React, { useState } from 'react';
import { Input } from '../../Base/Input/Input';
import { Button } from '../../Base/Buttons/Button';
import styles from './SignUp.module.css';
// import signup from '../../../assets/Signup.png';
import { getUserByPhone, postUser } from '../../../Api/userApi';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

export const SignUp = ({
  onSubmit,
  label = "SignUp",
  namePlaceholder = "Name",
  emailPlaceholder = "Email",
  phonePlaceholder = "Phone Number",
}) => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [errors, setErrors] = useState({ name: '', email: '', phoneNumber: '' });

  const handleNameChange = (e) => {
    setName(e.target.value);
    setErrors((prev) => ({ ...prev, name: '' }));
  };

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
    setErrors((prev) => ({ ...prev, email: '' }));
  };

  const handlePhoneChange = (e) => {
    setPhoneNumber(e.target.value);
    setErrors((prev) => ({ ...prev, phoneNumber: '' }));
  };

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

    if (!name.trim()) newErrors.name = 'Name is required';

    if (!email.trim()) {
      newErrors.email = 'Email is required';
    } else {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        newErrors.email = 'Enter a valid email address';
      }
    }

    if (!phoneNumber.trim()) {
      newErrors.phoneNumber = 'Phone number is required';
    } else if (phoneNumber.length < 10) {
      newErrors.phoneNumber = 'Phone number must contain at least 10 digits';
    } else {
      const phoneRegex = /^\+?\d{10,15}$/;
      if (!phoneRegex.test(phoneNumber)) {
        newErrors.phoneNumber = 'Phone number must contain only digits';
      }
    }

    setErrors(newErrors);

    if (Object.keys(newErrors).length === 0) {
      try {
        const res = await getUserByPhone(phoneNumber);
        if (res.data.length > 0) {
          setErrors((prev) => ({
            ...prev,
            phoneNumber: 'Phone number already registered',
          }));
          return;
        }

        const formData = { name, email, phoneNumber, reservedSeats: [] };
        const postRes = await postUser(formData);
           setName("");
          setEmail("");
          setPhoneNumber("");
        if (postRes.status === 201) {
          toast.success("Account created successfully!");
          if (onSubmit) onSubmit(formData);
        } else {
          toast.error("Something went wrong. Please try again.");
        }

      } catch (err) {
        console.error('Error submitting form:', err);
        toast.error("Network error or server not available.");
      }
    }
  };

  return (
    <div className={styles.SignUpContainer}>
      <div className={styles.wrapper}>
        {/* <div
          className={styles.leftPane}
          style={{ backgroundImage: `url(${signup})` }}
        ></div> */}

        <div className={styles.rightPane}>
          {/* <h1 className={styles.text}>Create Account</h1> */}
          <form onSubmit={handleSubmit} className={styles.form}>
            <Input
              type="text"
              placeholder={namePlaceholder}
              value={name}
              onChange={handleNameChange}
              errorMessage={errors.name}
              isInvalid={!!errors.name}
            />
            <Input
              type="text"
              placeholder={emailPlaceholder}
              value={email}
              onChange={handleEmailChange}
              errorMessage={errors.email}
              isInvalid={!!errors.email}
            />
            <Input
              type="text"
              placeholder={phonePlaceholder}
              value={phoneNumber}
              onChange={handlePhoneChange}
              errorMessage={errors.phoneNumber}
              isInvalid={!!errors.phoneNumber}
            />
            <Button variant="primary" label={label} size="md" />
          </form>
        </div>
      </div>
    </div>
  );
};
