"use client";

import React, { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Image from "next/image";
import MeetVector from "@/images/meet-vector.webp";
import MainBg from "@/images/main-bg.webp";

interface FormState {
  name: string;
  email: string;
  contact: string;
  password: string;
  confirm_password: string;
}

const RegisterPage = () => {
  const router = useRouter();

  const [formData, setFormData] = useState<FormState>({
    name: "",
    email: "",
    contact: "",
    password: "",
    confirm_password: "",
  });

  const [errors, setErrors] = useState<FormState>({
    name: "",
    email: "",
    contact: "",
    password: "",
    confirm_password: "",
  });

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  const validateField = (name: string, value: string, formState: FormState = formData): string => {
    switch (name) {
      case "name":
        if (!value.trim()) return "Full name is required";
        if (/\d/.test(value)) return "Name cannot contain numbers";
        if (!/^[a-zA-Z\s'-]+$/.test(value)) return "Name can only contain letters";
        return "";

      case "email":
        if (!value.trim()) return "Email is required";
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Please enter a valid email";
        return "";

      case "contact":
        if (!value.trim()) return "Contact number is required";
        if (value.length < 7) return "Please enter a valid contact number";
        return "";

      case "password":
        if (!value) return "Password is required";
        if (value.length < 8) return "Password must be at least 8 characters";
        if (!/[A-Z]/.test(value)) return "Password must contain at least one uppercase letter";
        if (!/[0-9]/.test(value)) return "Password must contain at least one number";
        return "";

      case "confirm_password":
        if (!value) return "Please confirm your password";
        if (value !== formState.password) return "Passwords do not match";
        return "";

      default:
        return "";
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    let updatedValue = value;

    if (name === "name") {
      updatedValue = value.replace(/[0-9]/g, "");
    }
    if (name === "contact") {
      updatedValue = value.replace(/\D/g, "").slice(0, 15);
    }

    const updatedForm = { ...formData, [name]: updatedValue };
    setFormData(updatedForm);

    const fieldError = validateField(name, updatedValue, updatedForm);
    setErrors((prev) => ({ ...prev, [name]: fieldError }));

    // Re-check confirm_password whenever password itself changes
    if (name === "password" && updatedForm.confirm_password) {
      setErrors((prev) => ({
        ...prev,
        confirm_password: validateField("confirm_password", updatedForm.confirm_password, updatedForm),
      }));
    }

    setError("");
    setMessage("");
  };

  const validateAll = (): boolean => {
    const newErrors: FormState = {
      name: validateField("name", formData.name),
      email: validateField("email", formData.email),
      contact: validateField("contact", formData.contact),
      password: validateField("password", formData.password),
      confirm_password: validateField("confirm_password", formData.confirm_password),
    };
    setErrors(newErrors);
    return !Object.values(newErrors).some((e) => e !== "");
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    setError("");
    setMessage("");

    if (!validateAll()) {
      setError("Please fill in all the required fields.");
      return;
    }

    setLoading(true);

    try {
      const response = await fetch("/api/student/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: formData.name.trim(),
          email: formData.email.trim(),
          contact: formData.contact.trim(),
          password: formData.password,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        setError(data.message || "Registration failed.");
        return;
      }

      setMessage(` ${data.message}`);

      setTimeout(() => {
        router.push("/student/login");
      }, 1500);
    } catch (err) {
      console.error(err);
      setError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <main
      className="mainsection"
      style={{
        backgroundImage: `url(${MainBg.src})`,
      }}
    >
      <section className="logincontainer">
        <div className="container">
          <div className="row justify-content-center">
            <div className="col-xxl-9 col-xl-10 col-lg-12 col-md-12 col-sm-12 col-12">
              <div className="logininner">
                <div className="row gx-xl-0">
                  <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 d-none d-md-block mb-3 mb-md-0">
                    <div className="loginleftbx">
                      <div className="w-100 position-relative z-index-1">
                        <h2>Welcome Back <br />Student!</h2>
                        <p>Rhythm Kuchipudi Dance Academy</p>
                        <p>Join Thousands of Students Learning the Art of Kuchipudi</p>
                      </div>
                      <div className="loginvector">
                        <Image src={MeetVector} alt="Vector" />
                      </div>
                    </div>
                  </div>
                  <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                    <div className="loginbx">
                      <h2>Student Registration</h2>

                      {error && (
                        <div className="alert alert-danger">
                          {error}
                        </div>
                      )}

                      {message && (
                        <div className="alert alert-success">
                          {message}
                        </div>
                      )}

                      <form className="loginform" onSubmit={handleSubmit} noValidate>
                        <div className="row gx-3">
                          <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                            <div className="form-group mb-3">
                              <label className="form-label">
                                Full Name
                              </label>
                              <div className="input-groups">
                                <span className="login-icon">
                                  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                                    <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6m2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0m4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4m-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10s-3.516.68-4.168 1.332c-.678.678-.83 1.418-.832 1.664z" />
                                  </svg>
                                </span>
                                <input
                                  type="text"
                                  name="name"
                                  className={`form-control ${errors.name ? "is-invalid" : formData.name ? "is-valid" : ""}`}
                                  value={formData.name}
                                  onChange={handleChange}
                                  placeholder="Enter full name"
                                />
                              </div>
                              {errors.name && (
                                <div className="invalid-feedback d-block">{errors.name}</div>
                              )}
                            </div>
                          </div>
                          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                            <div className="form-group mb-3">
                              <label className="form-label">
                                Email Address
                              </label>
                              <div className="input-groups">
                                <span className="login-icon">
                                  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                                    <path d="M0 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zm2-1a1 1 0 0 0-1 1v.217l7 4.2 7-4.2V4a1 1 0 0 0-1-1zm13 2.383-4.708 2.825L15 11.105zm-.034 6.876-5.64-3.471L8 9.583l-1.326-.795-5.64 3.47A1 1 0 0 0 2 13h12a1 1 0 0 0 .966-.741M1 11.105l4.708-2.897L1 5.383z" />
                                  </svg>
                                </span>
                                <input
                                  type="email"
                                  name="email"
                                  className={`form-control ${errors.email ? "is-invalid" : formData.email ? "is-valid" : ""}`}
                                  value={formData.email}
                                  onChange={handleChange}
                                  placeholder="Enter email"
                                />
                              </div>
                              {errors.email && (
                                <div className="invalid-feedback d-block">{errors.email}</div>
                              )}
                            </div>
                          </div>
                          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                            <div className="form-group mb-3">
                              <label className="form-label">
                                Contact Number
                              </label>
                              <div className="input-groups">
                                <span className="login-icon">
                                  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                                    <path d="M3.654 1.328a.678.678 0 0 0-1.015-.063L1.605 2.3c-.483.484-.661 1.169-.45 1.77a17.6 17.6 0 0 0 4.168 6.608 17.6 17.6 0 0 0 6.608 4.168c.601.211 1.286.033 1.77-.45l1.034-1.034a.678.678 0 0 0-.063-1.015l-2.307-1.794a.68.68 0 0 0-.58-.122l-2.19.547a1.75 1.75 0 0 1-1.657-.459L5.482 8.062a1.75 1.75 0 0 1-.46-1.657l.548-2.19a.68.68 0 0 0-.122-.58zM1.884.511a1.745 1.745 0 0 1 2.612.163L6.29 2.98c.329.423.445.974.315 1.494l-.547 2.19a.68.68 0 0 0 .178.643l2.457 2.457a.68.68 0 0 0 .644.178l2.189-.547a1.75 1.75 0 0 1 1.494.315l2.306 1.794c.829.645.905 1.87.163 2.611l-1.034 1.034c-.74.74-1.846 1.065-2.877.702a18.6 18.6 0 0 1-7.01-4.42 18.6 18.6 0 0 1-4.42-7.009c-.362-1.03-.037-2.137.703-2.877z" />
                                  </svg>
                                </span>
                                <input
                                  type="text"
                                  name="contact"
                                  className={`form-control ${errors.contact ? "is-invalid" : formData.contact ? "is-valid" : ""}`}
                                  value={formData.contact}
                                  onChange={handleChange}
                                  placeholder="Enter mobile number"
                                  maxLength={10}
                                />
                              </div>
                              {errors.contact && (
                                <div className="invalid-feedback d-block">{errors.contact}</div>
                              )}
                            </div>
                          </div>
                          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                            <div className="form-group mb-3">
                              <label className="form-label">
                                Password
                              </label>
                              <div className="input-groups">
                                <span className="login-icon">
                                  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd" d="M8 0a4 4 0 0 1 4 4v2.05a2.5 2.5 0 0 1 2 2.45v5a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 2 13.5v-5a2.5 2.5 0 0 1 2-2.45V4a4 4 0 0 1 4-4M4.5 7A1.5 1.5 0 0 0 3 8.5v5A1.5 1.5 0 0 0 4.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 11.5 7zM8 1a3 3 0 0 0-3 3v2h6V4a3 3 0 0 0-3-3" />
                                  </svg>
                                </span>
                                <input
                                  type={showPassword ? "text" : "password"}
                                  name="password"
                                  className={`form-control ${errors.password ? "is-invalid" : formData.password ? "is-valid" : ""}`}
                                  value={formData.password}
                                  onChange={handleChange}
                                  placeholder="Enter password"
                                />
                                <span
                                  className="login-icon login-icon-right"
                                  style={{ cursor: "pointer" }}
                                  onClick={() => setShowPassword(!showPassword)}
                                >
                                  <i className={`bi ${showPassword ? "bi-eye-slash" : "bi-eye"}`} />
                                </span>
                              </div>
                              {errors.password ? (
                                <div className="invalid-feedback d-block">{errors.password}</div>
                              ) : (
                                <div className="form-text text-muted" style={{ fontSize: "0.8rem" }}>
                                  Min 8 characters, one uppercase letter and one number
                                </div>
                              )}
                            </div>
                          </div>
                          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                            <div className="form-group mb-3">
                              <label className="form-label">
                                Confirm Password
                              </label>
                              <div className="input-groups">
                                <span className="login-icon">
                                  <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd" d="M8 0a4 4 0 0 1 4 4v2.05a2.5 2.5 0 0 1 2 2.45v5a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 2 13.5v-5a2.5 2.5 0 0 1 2-2.45V4a4 4 0 0 1 4-4M4.5 7A1.5 1.5 0 0 0 3 8.5v5A1.5 1.5 0 0 0 4.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 11.5 7zM8 1a3 3 0 0 0-3 3v2h6V4a3 3 0 0 0-3-3" />
                                  </svg>
                                </span>
                                <input
                                  type={showConfirmPassword ? "text" : "password"}
                                  name="confirm_password"
                                  className={`form-control ${errors.confirm_password ? "is-invalid" : formData.confirm_password ? "is-valid" : ""}`}
                                  value={formData.confirm_password}
                                  onChange={handleChange}
                                  placeholder="Confirm password"
                                />
                                <span
                                  className="login-icon login-icon-right"
                                  style={{ cursor: "pointer" }}
                                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                >
                                  <i className={`bi ${showConfirmPassword ? "bi-eye-slash" : "bi-eye"}`} />
                                </span>
                              </div>
                              {errors.confirm_password && (
                                <div className="invalid-feedback d-block">{errors.confirm_password}</div>
                              )}
                            </div>
                          </div>
                        </div>

                        <button
                          type="submit"
                          disabled={loading}
                          className="theme-btn"
                        >
                          {loading ? "Registering..." : "Register"}
                        </button>
                      </form>

                      <p className="donthaveaccount">Already have an account?{" "}<Link href="/student/login">Login</Link></p>

                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
};

export default RegisterPage;