"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import Link from "next/link";

export default function CreateStudent() {
  const router = useRouter();
  const [saving, setSaving] = useState(false);

  const [form, setForm] = useState({
    student_id: "",
    name: "",
    contact: "",
    email: "",
    password: "",
    confirm_password: "",
  });

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

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

  const validateField = (name: string, value: string): string => {
    switch (name) {
      case "student_id":
        if (!value.trim()) return "Student ID is required";
        return "";

      case "name":
        if (!value.trim()) return "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 "contact":
        if (!value) return "Contact number is required";
        if (value.length < 7) return "Please enter a valid contact number";
        return "";

      case "email":
        if (!value.trim()) return "Email is required";
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Please enter a valid email";
        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 !== form.password) return "Passwords do not match";
        return "";

      default:
        return "";
    }
  };

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

    // Block numbers in name
    if (name === "name") {
      updatedValue = value.replace(/[0-9]/g, "");
    }

    // Format phone
    if (name === "contact") {
      updatedValue = value.replace(/\D/g, "").slice(0, 15);
    }

    setForm((prev) => ({ ...prev, [name]: updatedValue }));

    // Validate on type
    const error = validateField(name, updatedValue);
    setErrors((prev) => ({ ...prev, [name]: error }));

    // Re-validate confirm password if password changes
    if (name === "password" && form.confirm_password) {
      setErrors((prev) => ({
        ...prev,
        confirm_password:
          form.confirm_password !== updatedValue ? "Passwords do not match" : "",
      }));
    }
  };

  const validateAll = () => {
    const newErrors = {
      student_id: validateField("student_id", form.student_id),
      name: validateField("name", form.name),
      contact: validateField("contact", form.contact),
      email: validateField("email", form.email),
      password: validateField("password", form.password),
      confirm_password: validateField("confirm_password", form.confirm_password),
    };

    setErrors(newErrors);
    return !Object.values(newErrors).some((e: string) => e !== "");
  };

  const handleSubmit = async () => {
    if (!validateAll()) return;

    try {
      setSaving(true);

      const res = await fetch("/api/admin/students", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          student_id: form.student_id,
          name: form.name,
          contact: form.contact.replace(/\D/g, ""), // send raw digits
          email: form.email,
          password: form.password,
        }),
      });

      const json = await res.json();

      if (json.success) {
        toast.success("Student created successfully");
        router.push("/admin/students");
      } else {
        toast.error(json.message || "Failed to create student");
      }
    } catch {
      toast.error("Failed to create student");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="admin-page-wrapper">
      {/* Header */}
      <div className="admin-page-header mb-4">
        <div className="d-flex justify-content-between align-items-center">
          <div>
            <h2 className="admin-page-title">Create Student</h2>
            <p className="admin-page-subtitle">Add a new student to the system</p>
          </div>
          <Link href="/admin/students" className="btn btn-light px-4">
            <i className="bi bi-arrow-left me-2" />
            Back to Students
          </Link>
        </div>
      </div>

      {/* Form Card */}
      <div className="card-theme p-4">
        <div className="row g-3">

          {/* Student ID */}
          <div className="col-md-6">
            <label className="form-label">
              Student ID <span className="text-danger">*</span>
            </label>
            <input
              type="text"
              className={`form-control ${errors.student_id ? "is-invalid" : form.student_id ? "is-valid" : ""}`}
              name="student_id"
              value={form.student_id}
              onChange={handleChange}
              placeholder="Enter student ID"
            />
            {errors.student_id && (
              <div className="invalid-feedback d-block">{errors.student_id}</div>
            )}
          </div>

          {/* Name */}
          <div className="col-md-6">
            <label className="form-label">
              Full Name <span className="text-danger">*</span>
            </label>
            <input
              type="text"
              className={`form-control ${errors.name ? "is-invalid" : form.name ? "is-valid" : ""}`}
              name="name"
              value={form.name}
              onChange={handleChange}
              placeholder="Enter full name"
            />
            {errors.name && (
              <div className="invalid-feedback d-block">{errors.name}</div>
            )}
          </div>

          {/* Email */}
          <div className="col-md-6">
            <label className="form-label">
              Email <span className="text-danger">*</span>
            </label>
            <input
              type="email"
              className={`form-control ${errors.email ? "is-invalid" : form.email ? "is-valid" : ""}`}
              name="email"
              value={form.email}
              onChange={handleChange}
              placeholder="Enter email address"
            />
            {errors.email && (
              <div className="invalid-feedback d-block">{errors.email}</div>
            )}
          </div>

          {/* Contact */}
          <div className="col-md-6">
            <label className="form-label">
              Contact Number <span className="text-danger">*</span>
            </label>
            <input
              type="text"
              className={`form-control ${errors.contact ? "is-invalid" : form.contact && !errors.contact ? "is-valid" : ""}`}
              name="contact"
              value={form.contact}
              onChange={handleChange}
              placeholder="Enter contact number"
              maxLength={14}
            />
            {errors.contact && (
              <div className="invalid-feedback d-block">{errors.contact}</div>
            )}
          </div>

          {/* Password */}
          <div className="col-md-6">
            <label className="form-label">
              Password <span className="text-danger">*</span>
            </label>
            <div className="input-group">
              <input
                type={showPassword ? "text" : "password"}
                className={`form-control ${errors.password ? "is-invalid" : form.password && !errors.password ? "is-valid" : ""}`}
                name="password"
                value={form.password}
                onChange={handleChange}
                placeholder="Enter password"
              />
              <button
                type="button"
                className="btn btn-outline-secondary"
                onClick={() => setShowPassword(!showPassword)}
                tabIndex={-1}
              >
                <i className={`bi ${showPassword ? "bi-eye-slash" : "bi-eye"}`} />
              </button>
            </div>
            {errors.password && (
              <div className="invalid-feedback d-block">{errors.password}</div>
            )}
            <div className="form-text text-muted">
              Min 8 characters, one uppercase letter and one number
            </div>
          </div>

          {/* Confirm Password */}
          <div className="col-md-6">
            <label className="form-label">
              Confirm Password <span className="text-danger">*</span>
            </label>
            <div className="input-group">
              <input
                type={showConfirmPassword ? "text" : "password"}
                className={`form-control ${errors.confirm_password ? "is-invalid" : form.confirm_password && !errors.confirm_password ? "is-valid" : ""}`}
                name="confirm_password"
                value={form.confirm_password}
                onChange={handleChange}
                placeholder="Confirm password"
              />
              <button
                type="button"
                className="btn btn-outline-secondary"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                tabIndex={-1}
              >
                <i className={`bi ${showConfirmPassword ? "bi-eye-slash" : "bi-eye"}`} />
              </button>
            </div>
            {errors.confirm_password && (
              <div className="invalid-feedback d-block">{errors.confirm_password}</div>
            )}
          </div>

        </div>

        {/* Actions */}
        <div className="d-flex justify-content-end gap-2 mt-4">
          <Link href="/admin/students" className="btn btn-light px-4">
            Cancel
          </Link>
          <button
            className="admin-theme-btn"
            onClick={handleSubmit}
            disabled={saving}
          >
            {saving ? (
              <><span className="spinner-border spinner-border-sm me-1" />Creating...</>
            ) : (
              <><i className="bi bi-plus-circle me-1" />Create Student</>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}