"use client";

import React, { useState } from "react";
import "./resetPassword.css";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { resetPasswordToken } from "../../../redux/services/auth/authServices";
import { useDispatch } from "react-redux";
import Swal from "sweetalert2";
import FormInput from "@/app/components/auth/commons/cards/Lable";
import HeaderCard from "@/app/components/auth/commons/cards/HeadingCard";
import SubHeaderCard from "@/app/components/auth/commons/cards/SubHeadingCard";
export const ResetTokenPassword = ({ token }: { token: any }) => {
  const router = useRouter();
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(false);
  const [newPassword, setNewPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [errors, setErrors] = useState({
    password: "",
    confirmPassword: "",
  });
  const validateForm = () => {
    const newErrors = {
      password: "",
      confirmPassword: "",
    };

    if (newPassword.length > 0 && newPassword.length < 8) {
      newErrors.password =
        "Le mot de passe doit contenir au moins 8 caractères";
    }
    if (newPassword !== confirmPassword) {
      newErrors.confirmPassword = "Les mots de passe ne correspondent pas";
    }

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

  const handlePasswordChange = (value: string) => {
    setNewPassword(value);
    if (confirmPassword) {
      validateForm();
    }
  };
  const handleBackClick = () => {
    router.back();
  };
  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: "Le mot de passe doit contenir au moins 8 caractères",
      }));
      return;
    }

    if (newPassword !== confirmPassword) {
      setErrors((prev) => ({
        ...prev,
        confirmPassword: "Les mots de passe ne correspondent pas",
      }));
      return;
    }

    setIsLoading(true);
    try {
      const result = await dispatch(
        resetPasswordToken({
          token,
          newPassword,
        }) as any
      ).unwrap();

      Swal.fire({
        icon: "success",
        title: "Mot de passe réinitialisé !",
        text:
          result.message ||
          "Votre mot de passe a été réinitialisé avec succès !",
        confirmButtonText: "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: "Échec de la réinitialisation",
        text: "",
        confirmButtonText: "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">
      <button
        className="mobile-back-reset-button"
        onClick={handleBackClick}
        aria-label="Go back"
      >
        <Image
          src="/login/arrow_email.png"
          alt="Retour"
          width={24}
          height={24}
          className="block-icon"
        />
      </button>
      <div className="reset-password-content">
        <HeaderCard
          logoSrc="/login/logo_1.png"
          logoAlt=""
          logoWidth={65}
          logoHeight={60}
          title=" Réinitialiser votre mot de passe"
          useOriginalStyling={true}
        />
        <SubHeaderCard
          line1="Créez un nouveau mot de passe pour votre compte"
          line2="Assurez-vous qu'il soit sécurisé et facile à mémoriser"
          useOriginalStyling={true}
        />
        <div className="email-input-container">
          <FormInput
            label="Mot de passe"
            name="password"
            type={showPassword ? "text" : "password"}
            value={newPassword}
            onChange={(fieldName, fieldValue) =>
              handlePasswordChange(fieldValue)
            }
            placeholder=""
            required
            error={errors.password}
            containerWidth="full"
          />
          <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">
          <FormInput
            label="Confirmer le mot de passe"
            name="confirmPassword" // Changed from "password" to "confirmPassword"
            type={showConfirmPassword ? "text" : "password"}
            value={confirmPassword}
            onChange={(fieldName, fieldValue) =>
              handleConfirmPasswordChange(fieldValue)
            }
            placeholder=""
            required
            autoComplete="new-password"
            error={errors.confirmPassword}
            containerWidth="full"
          />
          <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-reset-password-button">
          <button
            className="blue-reset-button"
            onClick={handleResetPassword}
            disabled={isLoading}
          >
            <span>
              {isLoading
                ? "Réinitialisation..."
                : "Réinitialiser le mot de passe"}
            </span>
            <Image
              src="/login/arrow.png" // Update with your actual arrow image path
              alt="Récupérer"
              width={16}
              height={16}
              className="button-icon"
              style={{ marginLeft: "5px" }}
            />
          </button>
        </div>
      </div>
    </div>
  );
};
