"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;
}

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: "",
    current_password: "",
    new_password: "",
    confirm_password: "",
  });

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

  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 || "",
      current_password: "",
      new_password: "",
      confirm_password: "",
    });
    setErrors({
      name: "",
      contact: "",
      email: "",
      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 "";

      // 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>) => {
    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 = { ...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),
      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;

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

    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);
      toast.success(data.message || "Profile updated successfully");
      setProfile(data.data);
      resetFormFromProfile(data.data);
      setEditing(false);
    } catch (err: any) {
      toast.error(err?.response?.data?.error ?? "Failed to update profile");
    } finally {
      setSaving(false);
    }
  };

  const cancelEdit = () => {
    if (profile) resetFormFromProfile(profile);
    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">
          <div className="row g-4">
            <div className="col-md-6">
              <p className="text-muted mb-1 small">Student ID</p>
              <p className="fw-semibold mb-0">{profile.student_id}</p>
            </div>

            <div className="col-md-6">
              <p className="text-muted mb-1 small">Full Name</p>
              <p className="fw-semibold mb-0">{profile.name}</p>
            </div>

            <div className="col-md-6">
              <p className="text-muted mb-1 small">Email Address</p>
              <p className="fw-semibold mb-0">{profile.email}</p>
            </div>

            <div className="col-md-6">
              <p className="text-muted mb-1 small">Contact Number</p>
              <p className="fw-semibold mb-0">{profile.contact}</p>
            </div>
          </div>
        </div>
      )}

      {/* EDIT MODE */}
      {editing && (
        <div className="card-theme p-4">
          <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 ? "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={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">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 ? "is-valid" : ""}`}
                  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 ? "is-valid" : ""}`}
                  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>
  );
}