import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";
import Image from "next/image";

  import { ToastContainer, toast } from 'react-toastify';


const BACKEND_API_URL = process.env.NEXT_PUBLIC_BACKEND_API_URL;

export default function VerifyOtp() {
  const router = useRouter();
  const inputsRef = useRef([]);

  const [otp, setOtp] = useState(Array(6).fill(""));
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [timer, setTimer] = useState(300);
  const [resending, setResending] = useState(false);

  const { token } = router.query;

  // Timer countdown
  useEffect(() => {
    if (timer === 0) return;
    const interval = setInterval(() => setTimer((t) => t - 1), 1000);
    return () => clearInterval(interval);
  }, [timer]);

  // Auto focus first input
  useEffect(() => {
    inputsRef.current[0]?.focus();
  }, []);

  useEffect(() => {
    if (!router.isReady) return; 
    if (token) {
      console.log("Token:", token);
      // use token here (API call, verification, etc.) 
      //check token time exceed or not


      const checkToken = async () => {

        try {

          const res = await fetch(`${BACKEND_API_URL}/users/check-otp-token`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ token: token }),
          });
          const response = await res.json();
          console.log(response)

          if (response.message == "success") {
            // showPage = true;
            // setShowPage(true);
            setShowDefault(true);
            setAmount(response.amount);

            setCancelURL(response.cancel_url);
            setFailedURL(response.failed_url);
            setSuccessURL(response.success_url);
          }
          else if (response.message == "token_expired") {
            // router.replace('/404')
            // setResending(true);
            setTimer(0);
            toast.error("Token Expired");
          }
          else if (response.message == "not_found") {
            router.replace('/404')
          }
          else {
            
          }
        } catch (err) {
          // console.log(err);
        }

      }

      checkToken();
    }
    else {
      router.replace('/404')
    }
  }, [router.isReady,token]);

  const handleChange = (value, index) => {
    if (!/^[0-9]?$/.test(value)) return;

    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);

    if (value && index < 5) {
      inputsRef.current[index + 1]?.focus();
    }
  };

  const handleKeyDown = (e, index) => {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      inputsRef.current[index - 1]?.focus();
    }
  };

  const handleSubmit = async () => {
    setError("");
    if (otp.join("").length !== 6) {
      setError("Please enter the 6-digit OTP");
      return;
    }

    try {
      setLoading(true);
      const res = await fetch(`${BACKEND_API_URL}/api/auth/verify-otp`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ otp: otp.join(""), token: token }),
      });

      const data = await res.json();
      if(data.status == "success"){
        toast.success("OTP Verified.Redirecting to login...");
        setTimeout(() => {
          router.replace('/login');
        }, 3000);
        
      }
      // else if(data.message == "token_expired"){
      //   toast.error("Token Expired.")
      // }
      else{
        toast.error(data.message);
        // toast.error("OTP Verification Failed.")
      }

      
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    try {
      setResending(true);
      setError("");

     

      const res = await fetch(`${BACKEND_API_URL}/api/auth/resend-otp`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token: token }),
      });

      const data = await res.json();

      if(data.status == "success"){
        toast.success("OTP Sent.");
        // router.replace('/login');
      }
      else{
        toast.error("Something Went Wrong. Try Again.")
      }

      // if (!res.ok) throw new Error(data.message || "Failed to resend OTP");

      setTimer(300);
    } catch (err) {
      setError(err.message);
    } finally {
      setResending(false);
    }
  };

  return (
    
    <div className="otp-page">
       {/* Gradient background */}
  {/* <div className="absolute inset-0 bg-gradient-to-r from-green-500 via-red-500 to-green-500"></div> */}

  {/* Dark overlay */}
  
      <ToastContainer />
      <div className="otp-card ">
        
        <div className="logo-wrapper">
          
          <Image src="/find_deshi transparent.png" alt="DeshiFinds Logo" width={140} height={50} />

        </div>

        <h1>Verify OTP</h1>
        <p className="subtitle">Enter the 6-digit code sent to your email</p>

        <div className="otp-inputs">
          
          {otp.map((digit, index) => (
            <input
            className="text-black"
              key={index}
              ref={(el) => (inputsRef.current[index] = el)}
              type="text"
              maxLength="1"
              value={digit}
              onChange={(e) => handleChange(e.target.value, index)}
              onKeyDown={(e) => handleKeyDown(e, index)}
            />
          ))}
        </div>

        {error && <p className="error">{error}</p>}

        <button className="submit-btn" onClick={handleSubmit} disabled={loading}>
          {loading ? "Verifying..." : "Verify OTP"}
        </button>

        <div className="resend-section">
          {timer > 0 ? (
            <span>Resend OTP in
              {timer > 60 ? <> {parseInt(timer / 60)}m {timer % 60}s</> : <>{timer}s</>}
            </span>
          ) : (
            <button
              className="resend-btn"
              onClick={handleResend}
              disabled={resending}
            >
              {resending ? "Sending..." : "Resend OTP"}
            </button>
          )}
        </div>
      </div>
      

      <style jsx>{`

      .logo-wrapper {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
      }

        .otp-page {
          min-height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
          background: linear-gradient(90deg, #22c55e 0%, #ef4444 50%, #22c55e 100%);
          padding: 20px;
        }

        .otp-card {
          background: #ffffff;
          padding: 40px 32px;
          border-radius: 16px;
          width: 100%;
          max-width: 420px;
          text-align: center;
          box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
        }

        h1 {
          margin-bottom: 8px;
          font-size: 26px;
          color: #1e293b;
        }

        .subtitle {
          font-size: 14px;
          color: #64748b;
          margin-bottom: 28px;
        }

        .otp-inputs {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
        }

        .otp-inputs input {
          width: 52px;
          height: 56px;
          border-radius: 10px;
          border: 2px solid #e2e8f0;
          font-size: 22px;
          text-align: center;
          outline: none;
          transition: all 0.2s ease;
        }

        .otp-inputs input:focus {
          border-color: #2563eb;
          box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
        }

        .error {
          color: #dc2626;
          font-size: 14px;
          margin-bottom: 12px;
        }

        .submit-btn {
          width: 100%;
          height: 48px;
          border-radius: 10px;
          border: none;
          background: #2563eb;
          color: #ffffff;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: background 0.2s ease;
        }

        .submit-btn:hover:not(:disabled) {
          background: #1d4ed8;
        }

        .submit-btn:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        .resend-section {
          margin-top: 18px;
          font-size: 14px;
          color: #475569;
        }

        .resend-btn {
          background: none;
          border: none;
          color: #2563eb;
          font-weight: 600;
          cursor: pointer;
        }

        .resend-btn:hover {
          text-decoration: underline;
        }
      `}</style>
    </div>
  );
}



// ⛔ No header / footer here
VerifyOtp.getLayout = function getLayout(page) {
  return page;
};