// import { Link, useNavigate } from 'react-router-dom';
// import { useDispatch, useSelector } from 'react-redux';
// import { IRootState } from '../../store';
// import { useEffect, useState } from 'react';
// import { setPageTitle, toggleRTL } from '../../store/themeConfigSlice';
// import Dropdown from '../../components/Dropdown';
// import i18next from 'i18next';
// import axios from 'axios'; // Import axios to make API calls
// import { showMessage } from '../../general';
// import {base_url} from '../../API';

// const RecoverIdBox = () => {
//     const dispatch = useDispatch();
//     const navigate = useNavigate();
//     const isRtl = useSelector((state: IRootState) => state.themeConfig.rtlClass) === 'rtl' ? true : false;
//     const themeConfig = useSelector((state: IRootState) => state.themeConfig);
//     const [flag, setFlag] = useState(themeConfig.locale);

//     const [email, setEmail] = useState('');
//     const [otp, setOtp] = useState('');
//     const [newPassword, setNewPassword] = useState('');
//     const [step, setStep] = useState(1); // To track the current step in the process
//     const [error, setError] = useState('');

//     useEffect(() => {
//         dispatch(setPageTitle('Recover Id Box'));
//     }, [dispatch]);

//     const setLocale = (flag: string) => {
//         setFlag(flag);
//         if (flag.toLowerCase() === 'ae') {
//             dispatch(toggleRTL('rtl'));
//         } else {
//             dispatch(toggleRTL('ltr'));
//         }
//     };

//     const handleEmailSubmit = async (e: React.FormEvent) => {
//         e.preventDefault();
//         try {

//             const response = await fetch(`${base_url}sendOtp`, {
//                 method: 'POST',
//                 body: JSON.stringify({ email:email,type:'web'}),
//                 headers: {
//                     'Accept': 'application/json',
//                     'Content-Type': 'application/json',
//                 },
//             });
//             const data = await response.json();

//             if (data.status === 'success') {
//                 showMessage(data.message, data.status);
//                 setStep(2); // Move to OTP step
//             }
//             else {

//                 showMessage(data.message, data.status);
//             }
//         } catch (error) {
//             setError('Failed to send recovery email. Please try again.');
//         }
//     };

//     const handleOtpSubmit = async (e: React.FormEvent) => {
//         e.preventDefault();
//         try {
//             // verifyOtp
//             const response = await fetch(`${base_url}verifyOtp`, {
//                 method: 'POST',
//                 body: JSON.stringify({ email:email,otp:otp,type:'web'}),
//                 headers: {
//                     'Accept': 'application/json',
//                     'Content-Type': 'application/json',
//                 },
//             });
//             const data = await response.json();

//             if (data.status === 'success') {
//                 showMessage(data.message, data.status);
//                 setStep(3); // Move to OTP step
//             }
//             else {

//                 showMessage(data.message, data.status);
//             }
//         } catch (error) {
//             setError('Invalid OTP. Please try again.');
//         }
//     };

//     const handlePasswordSubmit = async (e: React.FormEvent) => {
//         e.preventDefault();
//         try {
//             const response = await fetch(`${base_url}forgotpassword`, {
//                 method: 'POST',
//                 body: JSON.stringify({ email:email,password:newPassword,type:'web'}),
//                 headers: {
//                     'Accept': 'application/json',
//                     'Content-Type': 'application/json',
//                 },
//             });
//             const data = await response.json();

//             if (data.status === 'success') {
//                 showMessage(data.message, data.status);
//                 navigate('/login');
//             }
//             else {

//                 showMessage(data.message, data.status);
//             }
//         } catch (error) {
//             setError('Failed to reset password. Please try again.');
//         }
//     };

//     return (
//         <div>
//             <div className="absolute inset-0">
//                 <img src="/assets/images/auth/bg-gradient.png" alt="image" className="h-full w-full object-cover" />
//             </div>

//             <div className="relative flex min-h-screen items-center justify-center bg-[url(/assets/images/auth/map.png)] bg-cover bg-center bg-no-repeat px-6 py-10 dark:bg-[#060818] sm:px-16">
//                 <img src="/assets/images/auth/coming-soon-object1.png" alt="image" className="absolute left-0 top-1/2 h-full max-h-[893px] -translate-y-1/2" />
//                 <img src="/assets/images/auth/coming-soon-object2.png" alt="image" className="absolute left-24 top-0 h-40 md:left-[30%]" />
//                 <img src="/assets/images/auth/coming-soon-object3.png" alt="image" className="absolute right-0 top-0 h-[300px]" />
//                 <img src="/assets/images/auth/polygon-object.svg" alt="image" className="absolute bottom-0 end-[28%]" />
//                 <div className="relative w-full max-w-[870px] rounded-md bg-[linear-gradient(45deg,#fff9f9_0%,rgba(255,255,255,0)_25%,rgba(255,255,255,0)_75%,_#fff9f9_100%)] p-2 dark:bg-[linear-gradient(52.22deg,#0E1726_0%,rgba(14,23,38,0)_18.66%,rgba(14,23,38,0)_51.04%,rgba(14,23,38,0)_80.07%,#0E1726_100%)]">
//                     <div className="relative flex flex-col justify-center rounded-md bg-white/60 backdrop-blur-lg dark:bg-black/50 px-6 lg:min-h-[758px] py-20">
//                         <div className="mx-auto w-full max-w-[440px]">
//                             <div className="mb-7">
//                                 <h1 className="mb-3 text-2xl font-bold !leading-snug dark:text-white">{step === 1 ? 'Enter Your Email' : step === 2 ? 'Enter OTP' : 'Reset Password'}</h1>
//                                 {error && <p className="text-red-500">{error}</p>}
//                                 <p>{step === 1 ? 'Enter your email to recover your ID' : step === 2 ? 'Enter the OTP sent to your email' : 'Enter a new password'}</p>
//                             </div>
//                             <form onSubmit={step === 1 ? handleEmailSubmit : step === 2 ? handleOtpSubmit : handlePasswordSubmit} className="space-y-5">
//                                 {step === 1 && (
//                                     <div>
//                                         <label htmlFor="Email" className="dark:text-white">Email</label>
//                                         <div className="relative text-white-dark">
//                                             <input
//                                                 id="Email"
//                                                 type="email"
//                                                 placeholder="Enter Email"
//                                                 className="form-input ps-10 placeholder:text-white-dark"
//                                                 value={email}
//                                                 onChange={(e) => setEmail(e.target.value)}
//                                             />
//                                         </div>
//                                     </div>
//                                 )}
//                                 {step === 2 && (
//                                     <div>
//                                         <label htmlFor="Otp" className="dark:text-white">OTP</label>
//                                         <div className="relative text-white-dark">
//                                             <input
//                                                 id="Otp"
//                                                 type="text"
//                                                 placeholder="Enter OTP"
//                                                 className="form-input ps-10 placeholder:text-white-dark"
//                                                 value={otp}
//                                                 onChange={(e) => setOtp(e.target.value)}
//                                             />
//                                         </div>
//                                     </div>
//                                 )}
//                                 {step === 3 && (
//                                     <div>
//                                         <label htmlFor="Password" className="dark:text-white">New Password</label>
//                                         <div className="relative text-white-dark">
//                                             <input
//                                                 id="Password"
//                                                 type="password"
//                                                 placeholder="Enter New Password"
//                                                 className="form-input ps-10 placeholder:text-white-dark"
//                                                 value={newPassword}
//                                                 onChange={(e) => setNewPassword(e.target.value)}
//                                             />
//                                         </div>
//                                     </div>
//                                 )}
//                                 <button type="submit" className="btn btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)]">
//                                     {step === 1 ? 'SEND EMAIL' : step === 2 ? 'VERIFY OTP' : 'RESET PASSWORD'}
//                                 </button>
//                             </form>
//                         </div>
//                     </div>
//                 </div>
//             </div>
//         </div>
//     );
// };

// export default RecoverIdBox;



import { Link, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { useEffect, useState } from "react";
import { setPageTitle } from "../../store/themeConfigSlice";
import { showMessage } from "../../general";
import { base_url } from "../../API";

const RecoverIdBox = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [step, setStep] = useState(1); // Step 1: Email | Step 2: OTP | Step 3: Reset Password
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    dispatch(setPageTitle("Recover Account"));
  }, [dispatch]);

  // Step 1: Send Email
  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (!email.trim()) {
      setError("Email is required");
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(`${base_url}sendOtp`, {
        method: "POST",
        body: JSON.stringify({ email, type: "web" }),
        headers: { "Content-Type": "application/json" },
      });
      const data = await res.json();
      showMessage(data.message, data.status);
      if (data.status === "success") setStep(2);
    } catch {
      setError("Failed to send recovery email.");
    } finally {
      setLoading(false);
    }
  };

  // Step 2: Verify OTP
  const handleOtpSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (!otp.trim()) {
      setError("OTP is required");
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(`${base_url}verifyOtp`, {
        method: "POST",
        body: JSON.stringify({ email, otp, type: "web" }),
        headers: { "Content-Type": "application/json" },
      });
      const data = await res.json();
      showMessage(data.message, data.status);
      if (data.status === "success") setStep(3);
    } catch {
      setError("Invalid OTP. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  // Step 3: Reset Password
  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (!newPassword.trim()) {
      setError("Password is required");
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(`${base_url}forgotpassword`, {
        method: "POST",
        body: JSON.stringify({ email, password: newPassword, type: "web" }),
        headers: { "Content-Type": "application/json" },
      });
      const data = await res.json();
      showMessage(data.message, data.status);
      if (data.status === "success") navigate("/login");
    } catch {
      setError("Failed to reset password.");
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit =
    step === 1 ? handleEmailSubmit : step === 2 ? handleOtpSubmit : handlePasswordSubmit;

  return (
    <div className="flex min-h-screen">
      {/* LEFT SIDE - Logo + Branding (same as LoginBoxed) */}
      <div className="hidden lg:flex w-1/2 items-center justify-center bg-gradient-to-br from-primary via-primary-light to-secondary text-white p-12">
        <div className="text-center">
          <img
            src="/assets/images/ROWellnessSuitelogolite.png"
            alt="Logo"
            className="mx-auto mb-6 drop-shadow-lg"
          />
          <h2 className="text-4xl font-bold uppercase tracking-wide drop-shadow-lg">
            Recover Account
          </h2>
          <p className="mt-3 text-lg text-gray-100">
            Reset your password in just a few steps
          </p>
        </div>
      </div>

      {/* RIGHT SIDE - Recovery Form */}
      <div className="flex w-full lg:w-1/2 items-center justify-center bg-gray-100 lg:bg-transparent p-6">
        <div className="relative w-full max-w-md rounded-2xl border border-gray-200 bg-white backdrop-blur-xl shadow-2xl p-8">
          <div className="text-center mb-8">
            <h1 className="text-3xl md:text-4xl font-extrabold text-[#5e503f] uppercase drop-shadow-lg">
              {step === 1 ? "Recover ID" : step === 2 ? "Verify OTP" : "Reset Password"}
            </h1>
            <p className="mt-2 text-base font-medium text-gray-600">
              {step === 1
                ? "Enter your registered email"
                : step === 2
                ? "Enter the OTP sent to your email"
                : "Set a new password"}
            </p>
            {error && <p className="text-red-500 text-sm mt-2">{error}</p>}
          </div>

          <form className="space-y-5" onSubmit={handleSubmit}>
            {step === 1 && (
              <div>
                <label htmlFor="email" className="block text-sm font-semibold text-gray-700 mb-1">
                  Email
                </label>
                <input
                  id="email"
                  type="email"
                  placeholder="Enter Email"
                  className="w-full rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[#b19777]"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </div>
            )}

            {step === 2 && (
              <div>
                <label htmlFor="otp" className="block text-sm font-semibold text-gray-700 mb-1">
                  OTP
                </label>
                <input
                  id="otp"
                  type="text"
                  placeholder="Enter OTP"
                  className="w-full rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[#b19777]"
                  value={otp}
                  onChange={(e) => setOtp(e.target.value)}
                />
              </div>
            )}

            {step === 3 && (
              <div>
                <label
                  htmlFor="newPassword"
                  className="block text-sm font-semibold text-gray-700 mb-1"
                >
                  New Password
                </label>
                <input
                  id="newPassword"
                  type="password"
                  placeholder="Enter New Password"
                  className="w-full rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[#b19777]"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                />
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full rounded-lg bg-gradient-to-r from-[#b19777] via-[#c7b39c] to-[#5e503f] py-3 text-white font-semibold shadow-lg hover:opacity-90 transition uppercase"
            >
              {loading ? (
                <div className="w-5 h-5 border-t-2 border-white border-solid rounded-full animate-spin mx-auto"></div>
              ) : step === 1 ? (
                "Send OTP"
              ) : step === 2 ? (
                "Verify OTP"
              ) : (
                "Reset Password"
              )}
            </button>

            <div className="mt-3 text-sm text-center">
              <Link
                to="/login"
                className="text-[#5e503f] hover:underline hover:text-[#b19777]"
              >
                Back to Login
              </Link>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default RecoverIdBox;
