"use client";

import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import Link from "next/link";
import CustomLoader from "@/components/common/CustomLoader";
import axiosInstance from "@/lib/axiosInstance";

interface StudentProfile {
  id: number;
  student_id: string;
  name: string;
  contact: string;
  email: string;
  mother_first_name: string;
  mother_last_name: string;
  father_first_name: string;
  father_last_name: string;
  address: string;
}

export default function StudentProfilePage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editing, setEditing] = useState(false);

  const [profile, setProfile] = useState<StudentProfile | null>(null);

  const [form, setForm] = useState({
    name: "",
    contact: "",
    email: "",
    mother_first_name: "",
    mother_last_name: "",
    father_first_name: "",
    father_last_name: "",
    address: "",
    current_password: "",
    new_password: "",
    confirm_password: "",
  });

  const [errors, setErrors] = useState({
    name: "",
    contact: "",
    email: "",
    mother_first_name: "",
    mother_last_name: "",
    father_first_name: "",
    father_last_name: "",
    address: "",
    current_password: "",
    new_password: "",
    confirm_password: "",
  });
  const [submitError, setSubmitError] = useState("");

  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  useEffect(() => {
    loadProfile();
  }, []);

  const loadProfile = async () => {
    setLoading(true);
    try {
      const { data } = await axiosInstance.get("/student/profile");
      setProfile(data.data);
      resetFormFromProfile(data.data);
    } catch {
      toast.error("Failed to load profile");
    } finally {
      setLoading(false);
    }
  };

  const resetFormFromProfile = (p: StudentProfile) => {
    setForm({
      name: p.name || "",
      contact: p.contact || "",
      email: p.email || "",
      mother_first_name: p.mother_first_name || "",
      mother_last_name: p.mother_last_name || "",
      father_first_name: p.father_first_name || "",
      father_last_name: p.father_last_name || "",
      address: p.address || "",
      current_password: "",
      new_password: "",
      confirm_password: "",
    });
    setErrors({
      name: "",
      contact: "",
      email: "",
      mother_first_name: "",
      mother_last_name: "",
      father_first_name: "",
      father_last_name: "",
      address: "",
      current_password: "",
      new_password: "",
      confirm_password: "",
    });
  };

  const validateField = (name: string, value: string, formState = form) => {
    switch (name) {
      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 < 10) 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 "mother_first_name":
        if (!value.trim()) return "Mother's first name is required";
        if (!/^[a-zA-Z\s'-]+$/.test(value)) return "Name can only contain letters";
        return "";

      case "mother_last_name":
        if (!value.trim()) return "Mother's last name is required";
        if (!/^[a-zA-Z\s'-]+$/.test(value)) return "Name can only contain letters";
        return "";

      case "father_first_name":
        if (!value.trim()) return "Father's first name is required";
        if (!/^[a-zA-Z\s'-]+$/.test(value)) return "Name can only contain letters";
        return "";

      case "father_last_name":
        if (!value.trim()) return "Father's last name is required";
        if (!/^[a-zA-Z\s'-]+$/.test(value)) return "Name can only contain letters";
        return "";

      case "address":
        if (!value.trim()) return "Address is required";
        return "";

      // Password fields are optional as a group — only required/validated if the
      // student is actually attempting to change their password.
      case "current_password":
        if (!formState.new_password) return ""; // not required unless changing password
        if (!value) return "Enter your current password";
        return "";

      case "new_password":
        if (!value) return ""; // not 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 (!formState.new_password) return ""; // skip if no new password
        if (!value) return "Please confirm your new password";
        if (value !== formState.new_password) return "Passwords do not match";
        return "";

      default:
        return "";
    }
  };

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

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

    const updatedForm = { ...form, [name]: updatedValue };
    setForm(updatedForm);

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

    // Re-validate dependent fields when new_password changes
    if (name === "new_password") {
      setErrors((prev) => ({
        ...prev,
        current_password: validateField("current_password", updatedForm.current_password, updatedForm),
        confirm_password: validateField("confirm_password", updatedForm.confirm_password, updatedForm),
      }));
    }
  };

  const validateAll = () => {
    const newErrors = {
      name: validateField("name", form.name),
      contact: validateField("contact", form.contact),
      email: validateField("email", form.email),
      mother_first_name: validateField("mother_first_name", form.mother_first_name),
      mother_last_name: validateField("mother_last_name", form.mother_last_name),
      father_first_name: validateField("father_first_name", form.father_first_name),
      father_last_name: validateField("father_last_name", form.father_last_name),
      address: validateField("address", form.address),
      current_password: validateField("current_password", form.current_password),
      new_password: validateField("new_password", form.new_password),
      confirm_password: validateField("confirm_password", form.confirm_password),
    };
    setErrors(newErrors);
    return !Object.values(newErrors).some((e) => e !== "");
  };

  const handleSubmit = async () => {
    if (!validateAll()) return;
    setSubmitError(""); // clear previous error on new attempt

    const payload: Record<string, string> = {
      name: form.name,
      contact: form.contact.replace(/\D/g, ""),
      email: form.email,
      mother_first_name: form.mother_first_name,
      mother_last_name: form.mother_last_name,
      father_first_name: form.father_first_name,
      father_last_name: form.father_last_name,
      address: form.address,
    };

    if (form.new_password) {
      payload.current_password = form.current_password;
      payload.new_password = form.new_password;
    }

    try {
      setSaving(true);
      const { data } = await axiosInstance.put("/student/profile", payload);
      setProfile(data.data);
      resetFormFromProfile(data.data);
      setEditing(false);
    } catch (err: any) {
      const message = err?.response?.data?.error ?? "Failed to update profile";

      // If it's specifically a wrong-password error, attach it to that field
      // for a clearer inline experience; otherwise show it as a general banner.
      if (message.toLowerCase().includes("current password")) {
        setErrors((prev) => ({ ...prev, current_password: message }));
      } else {
        setSubmitError(message);
      }
    } finally {
      setSaving(false);
    }
  };

  const cancelEdit = () => {
    if (profile) resetFormFromProfile(profile);
    setSubmitError("");
    setEditing(false);
  };

  if (loading) {
    return <CustomLoader />;
  }

  if (!profile) {
    return (
      <div className="admin-page-wrapper">
        <p className="text-muted">Failed to load profile.</p>
      </div>
    );
  }

  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">My Profile</h2>
            <p className="admin-page-subtitle">
              {editing ? "Update your profile information" : "View your profile information"}
            </p>
          </div>

          {!editing && (
            <button className="admin-theme-btn" onClick={() => setEditing(true)}>
              <i className="bi bi-pencil me-1" />
              Edit Profile
            </button>
          )}
          {editing && (
            <button onClick={cancelEdit} className="btn btn-light px-4">
              <i className="bi bi-arrow-left me-2" />
              Back to Profile
            </button>
          )}
        </div>
      </div>

      {/* VIEW MODE */}
      {!editing && (
        <div className="card-theme p-4 p-md-4">
          <div className="row">
            <div className="col-md-12 mb-3">
              <h5 className="mb-0">Personal information</h5>
            </div>
            <div className="col-md-6 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-person-vcard"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Student ID</h4>
                    <p>{profile.student_id}</p>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-md-6 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-person"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Full Name</h4>
                    <p>{profile.name}</p>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-md-6 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-envelope"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Email Address</h4>
                    <p>{profile.email}</p>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-md-6 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-telephone"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Contact Number</h4>
                    <p>{profile.contact}</p>
                  </div>
                </div>
              </div>
            </div>
            <div className="col-md-12 mb-3 mt-3">
              <h5 className="mb-0">Family Details</h5>
            </div>
            <div className="col-md-6 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-person-heart"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Mother's Name</h4>
                    <p>
                      {profile.mother_first_name} {profile.mother_last_name}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-md-6 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-person-heart"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Father's Name</h4>
                    <p>
                      {profile.father_first_name} {profile.father_last_name}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-md-12 mb-4">
              <div className="userviewlist">
                <div className="d-flex gap-3">
                  <div className="userviewlisticon">
                    <i className="bi bi-geo-alt"></i>
                  </div>
                  <div className="flex-fill align-self-center">
                    <h4>Address</h4>
                    <p>{profile.address}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* EDIT MODE */}
      {editing && (
        <div className="card-theme p-4 p-md-4">
          {submitError && (
            <div className="alert alert-danger d-flex align-items-center gap-2" role="alert">
              <i className="bi bi-exclamation-circle" />
              <span>{submitError}</span>
            </div>
          )}
          <div className="row g-3">
            {/* Student ID — read-only, not editable by the student */}
            <div className="col-md-6">
              <label className="form-label">Student ID</label>
              <input type="text" className="form-control" value={profile.student_id} disabled />
            </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 ? "" : ""}`}
                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 ? "" : ""}`}
                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 ? "" : ""}`}
                name="contact"
                value={form.contact}
                onChange={handleChange}
                placeholder="Enter contact number"
                maxLength={10}
              />
              {errors.contact && <div className="invalid-feedback d-block">{errors.contact}</div>}
            </div>

            <div className="col-12">
              <hr className="my-2" />
              <p className="fw-semibold mb-0">Family & Address Details</p>
            </div>

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

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

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

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

            {/* Address */}
            <div className="col-md-12">
              <label className="form-label">
                Address <span className="text-danger">*</span>
              </label>
              <textarea
                className={`form-control ${errors.address ? "is-invalid" : form.address ? "" : ""}`}
                name="address"
                value={form.address}
                onChange={handleChange}
                placeholder="Enter address"
                rows={3}
              />
              {errors.address && <div className="invalid-feedback d-block">{errors.address}</div>}
            </div>

            <div className="col-12">
              <hr className="my-2" />
              <p className="fw-semibold mb-0">Change Password</p>
              <p className="text-muted small">Leave these blank to keep your current password.</p>
            </div>

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

            <div className="col-md-6 d-none d-md-block" />

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

            {/* Confirm New Password */}
            <div className="col-md-6">
              <label className="form-label">Confirm New Password</label>
              <div className="input-group">
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  className={`form-control ${errors.confirm_password ? "is-invalid" : form.confirm_password && !errors.confirm_password ? "" : ""}`}
                  name="confirm_password"
                  value={form.confirm_password}
                  onChange={handleChange}
                  placeholder="Confirm new 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">
            <button className="btn btn-light px-4" onClick={cancelEdit} disabled={saving}>
              Cancel
            </button>
            <button className="admin-theme-btn" onClick={handleSubmit} disabled={saving}>
              {saving ? (
                <>
                  <span className="spinner-border spinner-border-sm me-1" />
                  Saving...
                </>
              ) : (
                <>
                  <i className="bi bi-check-circle me-1" />
                  Save Changes
                </>
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}