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

export const SignUp = ({
  onSignUpSubmit,
  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 validateForm = () => {
    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);
    return Object.keys(newErrors).length === 0;
  };

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

    if (!validateForm()) return;

    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 };
      await onSignUpSubmit?.(formData);

      setName('');
      setEmail('');
      setPhoneNumber('');
    } catch (error) {
      toast.error("Something went wrong. Please try again.");
    }
  };

  return (
    <div className={styles.SignUpContainer}>
      <div className={styles.wrapper}>
        <div className={styles.rightPane}>
          <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>
  );
};
