"use client";

import React, { useState } from "react";
import "./resetPassword.css";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { resetPasswordCode } from "../../../redux/services/auth/authServices";
import { useDispatch } from "react-redux";
import Swal from "sweetalert2";
import { useResetPasswordData } from "@/app/hooks/useData";

export const ResetPassword = ({ email, code }: { email: any; code: any }) => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { data: translations } = useResetPasswordData();
  const t = translations || {};
  const [isLoading, setIsLoading] = useState(false);
  const [newPassword, setNewPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  console.log();
  const [errors, setErrors] = useState({
    password: "",
    confirmPassword: "",
  });
  const validateForm = () => {
    const newErrors = {
      password: "",
      confirmPassword: "",
    };

    if (newPassword.length > 0 && newPassword.length < 8) {
      newErrors.password =
        t.Form?.Password_Min_Length_Error ||
        "Password should be at least 8 characters long";
    }
    if (confirmPassword.length > 0 && newPassword !== confirmPassword) {
      newErrors.confirmPassword =
        t.Form?.Password_Mismatch_Error || "Passwords do not match";
    }

    setErrors(newErrors);
    return !newErrors.password && !newErrors.confirmPassword;
  };

  const handlePasswordChange = (value: string) => {
    setNewPassword(value);
    if (confirmPassword) {
      validateForm();
    }
  };

  const handleConfirmPasswordChange = (value: string) => {
    setConfirmPassword(value);
    if (newPassword) {
      validateForm();
    }
  };

  const handleResetPassword = async () => {
    setErrors({ password: "", confirmPassword: "" });

    // Validate form
    if (!validateForm()) {
      return;
    }
    if (newPassword.length < 8) {
      setErrors((prev) => ({
        ...prev,
        password:
          t.Form?.Password_Min_Length_Error ||
          "Password should be at least 8 characters long",
      }));
      return;
    }

    if (newPassword !== confirmPassword) {
      setErrors((prev) => ({
        ...prev,
        confirmPassword:
          t.Form?.Password_Mismatch_Error || "Passwords do not match",
      }));
      return;
    }

    setIsLoading(true);
    try {
      const result = await dispatch(
        resetPasswordCode({
          email,
          code,
          newPassword,
        }) as any
      ).unwrap();

      Swal.fire({
        icon: "success",
        title: t.SweetAlert?.Success_Title || "Password Reset!",
        text:
          result.message ||
          t.SweetAlert?.Success_Text ||
          "Your password has been reset successfully!",
        confirmButtonText: t.SweetAlert?.Success_Button || "OK",
      }).then(() => {
        // Redirect to login page after successful reset
        // router.push("/login");
      });
    } catch (error: unknown) {
      const errorMessage =
        error instanceof Error ? error.message : String(error);

      Swal.fire({
        icon: "error",
        title: t.SweetAlert?.Error_Title || "Reset Failed",
        text: errorMessage,
        confirmButtonText: t.SweetAlert?.Error_Button || "OK",
      });
    } finally {
      setIsLoading(false);
    }
  };
  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  const toggleConfirmPasswordVisibility = () => {
    setShowConfirmPassword(!showConfirmPassword);
  };

  const EyeOpenIcon = () => (
    <svg
      width="20"
      height="20"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
    >
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );

  const EyeClosedIcon = () => (
    <svg
      width="20"
      height="20"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
    >
      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
      <line x1="1" y1="1" x2="23" y2="23" />
    </svg>
  );
  return (
    <div className="white-reset-center-container">
      <div className="forgot-password-content">
        <div className="forgot-password-image">
          <Image
            src="/login/logo_1.png" // Update with your actual image path
            alt=""
            width={65}
            height={60}
          />
          <p className="forgot-password-title">
            {t.Page?.Title || "Reset your password?"}
          </p>
        </div>
        <div className="forgot-password-text">
          <p>
            {t.Page?.Description_Line1 ||
              "Create a new password for your account"}
          </p>
          <p>
            {t.Page?.Description_Line2 || "Make sure it's strong and memorable"}
          </p>
        </div>
        <div className="email-input-container">
          <label className="email-label">
            {t.Form?.Password_Label || "Password"}
          </label>
          <input
            type={showPassword ? "text" : "password"}
            className={`email-input ${errors.password ? "input-error" : ""}`}
            name="password"
            placeholder=""
            required
            autoComplete="new-password"
            value={newPassword}
            onChange={(e) => handlePasswordChange(e.target.value)}
          />
          <button
            type="button"
            className="password-toggle-btn"
            onClick={togglePasswordVisibility}
          >
            {showPassword ? <EyeClosedIcon /> : <EyeOpenIcon />}
          </button>
          {errors.password && newPassword.length < 8 && (
            <div
              className="error-message"
              style={{
                color: "red",
                fontSize: "12px",
                marginTop: "5px",
                textAlign: "left",
              }}
            >
              {errors.password}
            </div>
          )}
        </div>
        <div className="email-input-container">
          <label className="email-label">
            {t.Form?.Confirm_Password_Label || "Confirm Password"}
          </label>
          <input
            type={showConfirmPassword ? "text" : "password"}
            className={`email-input ${
              errors.confirmPassword ? "input-error" : ""
            }`}
            name="password"
            placeholder=""
            required
            autoComplete="new-password"
            value={confirmPassword}
            onChange={(e) => handleConfirmPasswordChange(e.target.value)}
          />
          <button
            type="button"
            className="password-toggle-btn"
            onClick={toggleConfirmPasswordVisibility}
          >
            {showConfirmPassword ? <EyeClosedIcon /> : <EyeOpenIcon />}
          </button>

          {errors.confirmPassword && newPassword !== confirmPassword && (
            <div
              className="error-message"
              style={{
                color: "red",
                fontSize: "12px",
                marginTop: "5px",
                textAlign: "left",
              }}
            >
              {errors.confirmPassword}
            </div>
          )}
        </div>
        <div className="retrieve-forget-password-button">
          <button
            className="blue-forget-button"
            onClick={handleResetPassword}
            disabled={isLoading}
          >
            <span>
              {isLoading
                ? t.Button?.Resetting || "Resetting..."
                : t.Button?.Reset_Password || "Reset Password"}
            </span>
            <Image
              src="/login/arrow.png" // Update with your actual arrow image path
              alt={t.Alt_Text?.Retrieve || "Retrieve"}
              width={16}
              height={16}
              className="button-icon"
              style={{ marginLeft: "5px" }}
            />
          </button>
        </div>
      </div>
    </div>
  );
};
