"use client";

import { useState } from "react";
import { useDispatch } from "react-redux";
import { Security } from "../../../api/api"; // Update with your correct path
import { Eye, EyeOff } from "lucide-react";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";

const SecuritySettings = () => {
  const [currentPassword, setCurrentPassword] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [success, setSuccess] = useState("");
  const [loading, setLoading] = useState(false);
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const dispatch = useDispatch<any>();
  const router = useRouter();

  // Password Validation Function
  const validatePassword = (password: string) => {
    if (password.length < 8)
      return "Password must be at least 8 characters long.";
    if (!/[A-Z]/.test(password))
      return "Password must contain at least one uppercase letter.";
    if (!/[a-z]/.test(password))
      return "Password must contain at least one lowercase letter.";
    if (!/[0-9]/.test(password))
      return "Password must contain at least one number.";
    if (!/[!@#$%^&*]/.test(password))
      return "Password must contain at least one special character (!@#$%^&*).";
    return "";
  };

  // Handle Save Password
  const handleSave = async () => {
    setErrors({});
    setSuccess("");

    const newErrors: { [key: string]: string } = {};

    // Validate Current Password
    if (!currentPassword) {
      newErrors.currentPassword = "Current password is required.";
    }
    // Validate New Password
    const passwordError = validatePassword(password);
    if (passwordError) {
      newErrors.password = passwordError;
    }
    // Validate New Password
    if (!password) {
      // console.log("entered here")
      newErrors.password = "Password is required.";
    }

    // Validate confirm Password
    if (!confirmPassword) {
      newErrors.confirmPassword = "Confirm password is required.";
    }

    // Check if New Password is different from Current Password
    if (password && password === currentPassword) {
      newErrors.password =
        "New password cannot be the same as the current password.";
    }

    // Check if Passwords Match
    if (password !== confirmPassword) {
      newErrors.confirmPassword = "Passwords do not match.";
    }


    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);

    try {
      const payload = {
        old_password: currentPassword,
        new_password: password,
      };

      const response = await dispatch(Security(payload)).unwrap();

      if (response?.success) {
        setSuccess("Password updated successfully!");
        toast.success("Password updated successfully!");

        setCurrentPassword("");
        setPassword("");
        setConfirmPassword("");
      } else {
        setErrors({
          apiError: response?.message || "Failed to update password.",
        });
      }
    } catch (error: any) {
      setErrors({ apiError: error.message || "Something went wrong." });
    } finally {
      setLoading(false);
    }
  };


  return (
    <div className="flex justify-center items-center p-2 pt-0">
      <div className="max-w-xl bg-white shadow-lg rounded-lg p-6 border border-gray-200 ">
        {/* <div className="w-[36rem] bg-white shadow-lg rounded-lg p-6 border border-gray-200 md:mt-6 xs:m-3"> */}
        <h2 className="text-2xl font-semibold mb-4 text-black text-center">
          Change Password
        </h2>
        <p className="text-base text-gray-500 mb-4 text-center">
          Change your password to keep your account secure.
        </p>

        {success && <p className="text-green-500 text-base mb-4">{success}</p>}
        {errors.apiError && (
          <p className="text-red-500 text-base mb-4 text-center">
            {errors.apiError}
          </p>
        )}

        {/* Current Password */}
        <div className="mb-4 relative">
          <label className="block text-base text-black font-medium text-start">
            Current Password <span className="text-red-600 text-2xl">*</span>
          </label>
          <input
            type={showCurrentPassword ? "text" : "password"}
            value={currentPassword}
            onChange={(e) => setCurrentPassword(e.target.value)}
            className="w-full p-2 border border-gray-300 rounded mt-1 pr-10"
            placeholder="Enter current password"
          />
          <button
            type="button"
            className="absolute right-3 top-10 text-gray-600 p-0"
            onClick={() => setShowCurrentPassword(!showCurrentPassword)}
          >
            {showCurrentPassword ? <EyeOff size={20} /> : <Eye size={20} />}
          </button>
          {errors.currentPassword && (
            <p className="text-red-500 text-sm mt-1 text-center">
              {errors.currentPassword}
            </p>
          )}
        </div>

        {/* New Password */}
        <div className="mb-4 relative">
          <label className="block text-base text-black font-medium text-start">
            New Password <span className="text-red-600 text-2xl">*</span>
          </label>
          <input
            type={showPassword ? "text" : "password"}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full p-2 border border-gray-300 rounded mt-1 pr-10"
            placeholder="Enter new password"
          />
          <button
            type="button"
            className="absolute right-3 top-10 text-gray-600 p-0"
            onClick={() => setShowPassword(!showPassword)}
          >
            {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
          </button>
          {errors.password && (
            <p className="text-red-500 text-sm mt-1 text-center">
              {errors.password}
            </p>
          )}
        </div>

        {/* Confirm Password */}
        <div className="mb-4 relative">
          <label className="block text-base text-black font-medium text-start">
            Confirm Password <span className="text-red-600 text-2xl">*</span>
          </label>
          <input
            type={showConfirmPassword ? "text" : "password"}
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            className="w-full p-2 border border-gray-300 rounded mt-1 pr-10"
            placeholder="Re-enter new password"
          />
          <button
            type="button"
            className="absolute right-3 top-10 text-gray-600 p-0"
            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
          >
            {showConfirmPassword ? <EyeOff size={20} /> : <Eye size={20} />}
          </button>
          {errors.confirmPassword && (
            <p className="text-red-500 text-sm mt-1 text-center">
              {errors.confirmPassword}
            </p>
          )}
        </div>
        <div className="text-start">
          <p
            className="text-start text-base font-semibold cursor-pointer mb-2 text-navy inline-block"
            onClick={() => router.push("/auth/forgot-password")}
          >
            Forgotten your password?
          </p>
        </div>

        {/* Save Button */}
        <button
          onClick={handleSave}
          className={`bg-navy text-white px-4 py-2 rounded w-full ${
            loading ? "opacity-50 cursor-not-allowed" : "hover:bg-navy"
          }`}
          disabled={loading}
        >
          {loading ? "Updating..." : "Update Password"}
        </button>
        {/* </div> */}
      </div>
    </div>
  );
};

export default SecuritySettings;
