// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/Anonymous/Login/VerifyOTT.jsx
import { useState, useEffect } from "react";
import { Link, useSearchParams, useNavigate } from "react-router-dom";
import Page from "../../../components/Page";
import { VerifyOTT as VerifyOTTAPI } from "../../../../wailsjs/go/app/Application";

function VerifyOTT() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [ott, setOtt] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  useEffect(() => {
    // Get email from URL query parameter
    const emailParam = searchParams.get("email");
    if (emailParam) {
      setEmail(emailParam);
    }
  }, [searchParams]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setMessage("");
    setLoading(true);

    if (!email) {
      setError("Email is missing. Please return to login.");
      setLoading(false);
      return;
    }

    if (!ott) {
      setError("Please enter the one-time token.");
      setLoading(false);
      return;
    }

    try {
      // Verify OTT - this returns the encrypted challenge and user keys
      const response = await VerifyOTTAPI(email, ott);
      setMessage("Token verified! Redirecting...");

      // Store the challenge data in sessionStorage to pass to CompleteLogin
      sessionStorage.setItem(
        "loginChallenge",
        JSON.stringify({
          email: email,
          challengeId: response.challengeId,
          encryptedChallenge: response.encryptedChallenge,
          salt: response.salt,
          encryptedMasterKey: response.encryptedMasterKey,
          encryptedPrivateKey: response.encryptedPrivateKey,
          publicKey: response.publicKey,
          // Include KDF algorithm
          kdfAlgorithm: response.kdfAlgorithm || "PBKDF2-SHA256",
        }),
      );

      // Redirect to complete login page
      setTimeout(() => {
        navigate("/login/complete");
      }, 1000);
    } catch (err) {
      const errorMessage = err.message || err.toString();

      // Try to parse RFC 9457 format
      try {
        const jsonMatch = errorMessage.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          const problemDetails = JSON.parse(jsonMatch[0]);
          setError(
            problemDetails.detail || problemDetails.title || errorMessage,
          );
        } else {
          setError("Verification failed: " + errorMessage);
        }
      } catch (parseErr) {
        setError("Verification failed: " + errorMessage);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page title="Verify Token" showBackButton={true}>
      <form onSubmit={handleSubmit} style={{ maxWidth: "400px" }}>
        <p style={{ marginBottom: "20px", color: "#333" }}>
          Enter the one-time token sent to <strong>{email}</strong>.
        </p>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="email"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Email
          </label>
          <input
            type="email"
            id="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            style={{
              width: "100%",
              padding: "8px",
              backgroundColor: "#f5f5f5",
            }}
            readOnly
          />
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="ott"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            One-Time Token
          </label>
          <input
            type="text"
            id="ott"
            value={ott}
            onChange={(e) => setOtt(e.target.value)}
            placeholder="Enter token from email"
            style={{ width: "100%", padding: "8px" }}
            autoFocus
          />
        </div>

        {error && <p style={{ color: "red", marginBottom: "15px" }}>{error}</p>}
        {message && (
          <p style={{ color: "green", marginBottom: "15px" }}>{message}</p>
        )}

        <div className="nav-buttons">
          <button type="submit" className="nav-button" disabled={loading}>
            {loading ? "Verifying..." : "Verify Token"}
          </button>
          <Link to="/login" className="nav-button secondary">
            Back to Login
          </Link>
        </div>

        <div
          style={{
            marginTop: "20px",
            padding: "10px",
            background: "#f0f0f0",
            borderRadius: "5px",
          }}
        >
          <p style={{ margin: 0, fontSize: "14px", color: "#666" }}>
            <strong>Didn't receive the token?</strong> Check your spam folder or
            return to login to request a new one.
          </p>
        </div>
      </form>
    </Page>
  );
}

export default VerifyOTT;
