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

function InitiateRecovery() {
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

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

    try {
      // Validate email
      if (!email) {
        throw new Error("Email address is required");
      }

      if (!email.includes("@")) {
        throw new Error("Please enter a valid email address");
      }

      console.log("[InitiateRecovery] Starting recovery process for:", email);

      // Call backend to initiate recovery
      const response = await InitiateRecoveryAPI(email);

      console.log("[InitiateRecovery] Recovery initiated successfully");
      console.log("[InitiateRecovery] session_id:", response.sessionId);

      // Check if session was actually created
      if (!response.sessionId || !response.encryptedChallenge) {
        // User not found - show generic message for security
        setError(
          "Unable to initiate recovery. Please ensure you entered the correct email address associated with your account."
        );
        return;
      }

      // Store recovery session data in sessionStorage for the verify step
      sessionStorage.setItem("recoveryEmail", email);
      sessionStorage.setItem("recoverySessionId", response.sessionId);
      sessionStorage.setItem("recoveryEncryptedChallenge", response.encryptedChallenge);

      // Navigate to verification step
      navigate("/recovery/verify");
    } catch (err) {
      console.error("[InitiateRecovery] Recovery initiation failed:", err);
      setError(err.message || "Failed to initiate recovery");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page title="Account Recovery" showBackButton={true}>
      <div style={{ maxWidth: "500px" }}>
        {/* Warning Banner */}
        <div
          style={{
            background: "#fff3cd",
            border: "1px solid #ffc107",
            borderRadius: "8px",
            padding: "15px",
            marginBottom: "20px",
          }}
        >
          <strong style={{ color: "#856404" }}>Before You Begin</strong>
          <p style={{ margin: "10px 0 0", color: "#856404", fontSize: "14px" }}>
            You'll need your <strong>12-word recovery phrase</strong> to complete
            this process. Make sure you have it ready before proceeding.
          </p>
        </div>

        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: "15px" }}>
            <label
              htmlFor="email"
              style={{
                display: "block",
                marginBottom: "5px",
                fontWeight: "bold",
                color: "#333",
              }}
            >
              Email Address
            </label>
            <input
              type="email"
              id="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter your email address"
              required
              disabled={loading}
              style={{ width: "100%", padding: "8px" }}
            />
            <small style={{ display: "block", marginTop: "5px", color: "#666" }}>
              We'll use this to verify your identity and guide you through recovery
            </small>
          </div>

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

          <div className="nav-buttons">
            <button type="submit" className="nav-button" disabled={loading}>
              {loading ? "Starting Recovery..." : "Start Account Recovery"}
            </button>
            <Link to="/login" className="nav-button secondary">
              Back to Login
            </Link>
          </div>
        </form>

        {/* Security Note */}
        <div
          style={{
            marginTop: "20px",
            padding: "10px",
            background: "#f0f0f0",
            borderRadius: "5px",
          }}
        >
          <strong>Security Note:</strong> Your recovery phrase is the only way to
          recover your account if you forget your password. It is never stored on
          our servers.
        </div>
      </div>
    </Page>
  );
}

export default InitiateRecovery;
