import React, { useState } from "react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import showToast from "../../services/toastService";
import AuthRepository from "../../repositories/AuthRepository";
import "./page-auth.css";
import { useSelector } from "react-redux";

// --- Zod Schema for validation ---
const ChangePasswordSchema = z
  .object({
    newPassword: z
      .string()
      .min(8, "Password must be at least 8 characters")
      .regex(/[A-Z]/, "Must contain an uppercase letter")
      .regex(/[a-z]/, "Must contain a lowercase letter")
      .regex(/\d/, "Must contain a number")
      .regex(
        /[!@#$%^&*()_+{}\[\]:;<>,.?~\\/-]/,
        "Must contain a special character"
      ),
    confirmPassword: z.string().min(1, "Confirm Password is required"),
    oldPassword: z.string().min(1, "Old Password is required"),
  })
  .refine((data) => data.newPassword === data.confirmPassword, {
    message: "New password and Confirm password do not match",
    path: ["confirmPassword"],
  });

const ChangePasswordPage = ({ onClose }) => {
  const [loading, setLoading] = useState(false);
  const [hideOldPass, setHideOldPass] = useState(true);
  const [hideNewPass, setHideNewPass] = useState(true);
  const [hideConfirmPass, setHideConfirmPass] = useState(true);
  const loggedUser = useSelector((store) => store.globalVariables.loginUser);

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setError,
  } = useForm({
    resolver: zodResolver(ChangePasswordSchema),
  });

  const onChangePassword = async (data) => {
    try {
      let formData = {
        email: loggedUser?.employeeInfo?.email,
        oldPassword: data.oldPassword,
        newPassword: data.newPassword,
      };
      setLoading(true);
      await AuthRepository.changepassword(formData);
      showToast("Your Password changed Successfully", "success");
      setLoading(false);
      reset();
      onClose();
    } catch (error) {
      setLoading(false);
      showToast(error.response.data.message, "error");
    }
  };

  return (
    <div
      className="modal d-flex align-items-center justify-content-center show"
      tabIndex="-1"
      role="dialog"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
    >
      <div className="modal-dialog" role="document">
        <div className="modal-content p-10 rounded shadow bg-white position-relative">
          <button
            type="button"
            className="btn-close"
            data-bs-dismiss="modal" aria-label="Close"
            onClick={onClose} // Use onClick to trigger onClose function
            style={{ position: "absolute", top: "15px", right: "15px" }} // Example positioning
          ></button>

          <h5 className="mb-2">Change Password</h5>
          <p className="mb-4" style={{ fontSize: "14px" }}>
            Enter old and new password to update.
          </p>

          <form onSubmit={handleSubmit(onChangePassword)}>
            {/* Old Password */}
            <div className="mb-3 text-start">
              <label className="form-label">Old Password</label>
              <div className="input-group input-group-merge d-flex align-items-center border rounded px-2">
                <input
                  type={hideOldPass ? "password" : "text"}
                  className="form-control form-control-sm border-0 shadow-none"
                  {...register("oldPassword")}
                  placeholder="&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;"
                  style={{ flex: 1 }}
                />
                <button
                  type="button"
                  className="btn btn-link p-0 ms-2"
                  style={{ fontSize: "18px", color: "#6c757d" }}
                  onClick={() => setHideOldPass(!hideOldPass)}
                >
                  <i className={`bx ${hideOldPass ? "bx-hide" : "bx-show"}`} />
                </button>
              </div>
              {errors.oldPassword && (
                <p className="danger-text small-text text-start">
                  {errors.oldPassword.message}
                </p>
              )}
            </div>

            <div className="mb-3 text-start">
              <label className="form-label">New Password</label>
              <div className="input-group input-group-merge d-flex align-items-center border rounded px-2">
                <input
                  type={hideNewPass ? "password" : "text"}
                  className="form-control form-control-sm border-0 shadow-none"
                  {...register("newPassword")}
                  placeholder="&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;"
                  style={{ flex: 1 }}
                />
                <button
                  type="button"
                  className="btn btn-link p-0 ms-2"
                  style={{ fontSize: "18px", color: "#6c757d" }}
                  onClick={() => setHideNewPass(!hideNewPass)}
                >
                  <i className={`bx ${hideNewPass ? "bx-hide" : "bx-show"}`} />
                </button>
              </div>
              {errors.newPassword && (
                <div
                  className="danger-text text-start"
                  style={{ fontSize: "12px" }}
                >
                  {errors.newPassword.message}
                </div>
              )}
            </div>

            {/* Confirm Password */}
            <div className="mb-3 text-start">
              <label className="form-label">Confirm New Password</label>
              <div className="input-group input-group-merge d-flex align-items-center border rounded px-2">
                <input
                  type={hideConfirmPass ? "password" : "text"}
                  className="form-control form-control-sm border-0 shadow-none"
                  {...register("confirmPassword")}
                  placeholder="&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;"
                  style={{ flex: 1 }}
                />
                <button
                  type="button"
                  className="btn btn-link p-0 ms-2"
                  style={{ fontSize: "18px", color: "#6c757d" }}
                  onClick={() => setHideConfirmPass(!hideConfirmPass)}
                >
                  <i
                    className={`bx ${hideConfirmPass ? "bx-hide" : "bx-show"}`}
                  />
                </button>
              </div>
              {errors.confirmPassword && (
                <div
                  className="danger-text text-start"
                  style={{ fontSize: "12px" }}
                >
                  {errors.confirmPassword.message}
                </div>
              )}
            </div>

            <div className="d-flex justify-content-center pt-2 text-muted small">
              Your password must have at least 8 characters and include a lower
              case letter, an uppercase letter, a number, and a special
              character.
            </div>
            {/* Action Buttons */}
            <div className="d-flex justify-content-center pt-4">
              <button
                type="submit"
                className="btn btn-primary btn-sm me-2"
                disabled={loading}
              >
                {loading ? "Please Wait..." : "Change Password"}
              </button>
              <button
                type="button"
                className="btn btn-outline-secondary btn-sm"
                onClick={onClose}
                disabled={loading}
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ChangePasswordPage;