import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import LoadingIcons from "react-loading-icons";
import { register } from "../redux/features/authSlice";
import "../register.css";
import Footer from "./Footer";
import Navbar from "./Navbar";
import "primeicons/primeicons.css";

const initialState = {
  title: "None",
  firstName: "",
  middleName: "",
  lastName: "",
  email: "",
  password: "",
  confirmPassword: "",
  termsconditions: "",
  userType: "", // New field for radio button selection
};

const Register = () => {
  const [formValue, setFormValue] = useState(initialState);
  const [isFormValid, setIsFormValid] = useState(false); // New state variable
  const { loading, error } = useSelector((state) => ({ ...state.auth }));
  const {
    title,
    email,
    password,
    firstName,
    middleName,
    lastName,
    confirmPassword,
    termsconditions,
    userType,
  } = formValue; // include userType
  const dispatch = useDispatch();
  const navigate = useNavigate();

  useEffect(() => {
    error && toast.error(error);
  }, [error]);

  useEffect(() => {
    // Check if all fields are filled and radio button is selected
    const isValid =
      title !== "None" &&
      email &&
      password &&
      firstName &&
      middleName &&
      lastName &&
      confirmPassword &&
      termsconditions &&
      userType !== ""; // Validate userType selection

    setIsFormValid(isValid);
  }, [
    title,
    email,
    password,
    firstName,
    middleName,
    lastName,
    confirmPassword,
    termsconditions,
    userType,
  ]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      return toast.error("Password should match");
    }
    if (isFormValid) {
      dispatch(register({ formValue, navigate, toast }));
    } else {
      toast.error("Please fill in all fields and select all checkboxes");
    }
  };

  const capitalizeFirstLetter = (str) => {
    return str.charAt(0).toUpperCase() + str.slice(1);
  };

  const onInputChange = (e) => {
    const { name, value, type, checked } = e.target;

    if (type === "checkbox") {
      // Set to true if checked, false if unchecked
      setFormValue((prevData) => ({
        ...prevData,
        [name]: checked,
      }));
    } else {
      setFormValue((prevData) => ({
        ...prevData,
        [name]:
          name === "email" || name === "password" || name === "confirmPassword"
            ? value
            : capitalizeFirstLetter(value),
      }));
    }
  };

  // New handler for radio buttons
  const handleUserTypeChange = (e) => {
    setFormValue((prevData) => ({
      ...prevData,
      userType: e.target.value,
    }));
  };

  return (
    <>
      <Navbar />
      <br />
      <br />
      <br />
      <br />
      <br />
      <section
        className="card"
        style={{ minHeight: "100vh", backgroundColor: "#FFFFFF" }}
      >
        <div className="container-fluid px-0">
          <div className="row gy-4 align-items-center justify-content-center">
            <div className="col-12 col-md-0 col-xl-20 text-center text-md-start">
              {/* <i
                className="fa fa-dollar"
                style={{ fontSize: "2.5rem", color: "#fda417" }}
                aria-hidden="true"
              /> */}
              {/* <div className="text-bg-primary">
                <div className="px-4">
                  <hr className="border-primary-subtle mb-4" />
                  <h2 className="h1 mb-4">Empower your investors</h2>
                  <p className="lead mb-5">
                    A beautiful, easy-to-use, and secure Investor Portal that
                    gives your investors everything they may need
                  </p>
                  <div className="text-endx">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width={48}
                      height={48}
                      fill="currentColor"
                      className="bi bi-grip-horizontal"
                      viewBox="0 0 16 16"
                    >
                      <path d="M2 8a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0-3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm3 3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0-3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm3 3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0-3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm3 3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0-3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm3 3a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm0-3a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
                    </svg>
                  </div>
                </div>
              </div> */}
            </div>

            <div className="col-12 col-md-6 col-xl-5">
              <div
                className="card border-0 rounded-4 shadow-lg"
                style={{ width: "100%" }}
              >
                <div className="card-body p-3 p-md-4 p-xl-5">
                  <div className="row">
                    <div className="col-12">
                      <div className="mb-4">
                        <h2 className="h3">Registration</h2>
                        <h3 style={{ color: "red" }}>
                          All fields are mandatory to enable "Sign up"
                        </h3>
                        <hr />
                      </div>
                    </div>
                  </div>
                  
                  <form onSubmit={handleSubmit}>
                    <div className="row gy-3 overflow-hidden">
                      {/* Radio buttons for Lender and Borrower */}
                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <label className="form-label">
                            Please select the role. <br />
                            <br />
                          </label>
                          <div className="form-check form-check-inline">
                            <input
                              className="form-check-input"
                              type="radio"
                              name="userType"
                              value="Lender"
                              checked={userType === "Lender"}
                              onChange={handleUserTypeChange}
                              required
                            />
                            <label className="form-check-label">Lender</label>
                          </div>
                          <div className="form-check form-check-inline">
                            <input
                              className="form-check-input"
                              type="radio"
                              name="userType"
                              value="Borrower"
                              checked={userType === "Borrower"}
                              onChange={handleUserTypeChange}
                              required
                            />
                            <label className="form-check-label">
                              Borrower{" "}
                            </label>
                            <br />
                            <br />
                          </div>
                        </div>
                      </div>

                      <div className="col-12">
                        <select
                          className="form-floating mb-3 form-control"
                          aria-label="Default select example"
                          name="title"
                          value={title}
                          onChange={onInputChange}
                        >
                          <option value="None">Please Select Title</option>
                          <option value="Dr">Dr</option>
                          <option value="Prof">Prof</option>
                          <option value="Mr">Mr</option>
                          <option value="Miss">Miss</option>
                        </select>
                        {/* <label htmlFor="Select" className="form-label">
                      {title === "Select" ? (
                        <span>You selected {title}</span>
                      ) : (
                        `You selected ${title}`
                      )}
                          </label> */}
                        <br />
                      </div>

                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <input
                            type="text"
                            className="form-control"
                            value={firstName}
                            name="firstName"
                            onChange={onInputChange}
                            placeholder="First Name"
                            required="required"
                          />

                          <label htmlFor="firstName" className="form-label">
                            First Name
                          </label>
                        </div>
                      </div>

                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <input
                            type="text"
                            className="form-control"
                            value={middleName}
                            name="middleName"
                            onChange={onInputChange}
                            placeholder="Middle Name"
                            required="required"
                          />

                          <label htmlFor="middleName" className="form-label">
                            Middle Name
                          </label>
                        </div>
                      </div>

                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <input
                            type="text"
                            className="form-control"
                            value={lastName}
                            name="lastName"
                            onChange={onInputChange}
                            placeholder="Last Name"
                            required="required"
                          />

                          <label htmlFor="lastName" className="form-label">
                            Last Name
                          </label>
                        </div>
                      </div>
                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <input
                            type="email"
                            className="form-control"
                            value={email}
                            name="email"
                            onChange={onInputChange}
                            placeholder="name@example.com"
                            required="required"
                          />
                          <label htmlFor="email" className="form-label">
                            Email
                          </label>
                        </div>
                      </div>
                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <input
                            type="password"
                            className="form-control"
                            value={password}
                            name="password"
                            onChange={onInputChange}
                            placeholder="Password"
                            required="required"
                          />

                          <label htmlFor="password" className="form-label">
                            Password
                          </label>
                        </div>
                      </div>

                      <div className="col-12">
                        <div className="form-floating mb-3">
                          <input
                            type="password"
                            className="form-control"
                            value={confirmPassword}
                            name="confirmPassword"
                            onChange={onInputChange}
                            placeholder="confirmPassword"
                            required="required"
                          />
                          <label htmlFor="password" className="form-label">
                            Retype Password
                          </label>
                        </div>
                      </div>

                      <div className="col-12">
                        <div className="form-check">
                          <input
                            className="form-check-input"
                            type="checkbox"
                            id="termsconditions"
                            value={termsconditions}
                            name="termsconditions"
                            checked={termsconditions}
                            onChange={onInputChange}
                            required
                          />
                          <label
                            className="form-check-label text-secondary"
                            htmlFor="iAgree"
                          >
                            I agree to the{" "}
                            <a
                              href="#!"
                              className="link-primary text-decoration-none"
                            >
                              terms and conditions
                            </a>
                          </label>
                        </div>
                      </div>

                      <div className="col-12">
                        <div className="d-grid">
                          <button
                            className="btn btn-primary btn-lg"
                            type="submit"
                            style={{
                              backgroundColor: "#fda417",
                              border: "#fda417",
                            }}
                            disabled={!isFormValid || loading}
                          >
                            {loading && <LoadingIcons.Bars />}
                            Sign up
                          </button>
                        </div>
                      </div>
                    </div>
                  </form>
                  <div className="row">
                    <div className="col-12">
                      <div className="d-flex gap-2 gap-md-4 flex-column flex-md-row justify-content-md-end mt-4">
                        <p className="m-0 text-secondary text-center">
                          Already have an account?{" "}
                          <a
                            href="#!"
                            className="link-primary text-decoration-none"
                          >
                            Sign in
                          </a>
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="row">
                    <div className="col-12"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      <Footer />
    </>
  );
};

export default Register;
