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

function VerifyRecovery() {
  const navigate = useNavigate();
  const [recoveryPhrase, setRecoveryPhrase] = useState("");
  const [loading, setLoading] = useState(false);
  const [decrypting, setDecrypting] = useState(false);
  const [error, setError] = useState("");
  const [email, setEmail] = useState("");
  const [sessionId, setSessionId] = useState("");
  const [encryptedChallenge, setEncryptedChallenge] = useState("");
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    // Get recovery session data from sessionStorage
    const storedEmail = sessionStorage.getItem("recoveryEmail");
    const storedSessionId = sessionStorage.getItem("recoverySessionId");
    const storedChallenge = sessionStorage.getItem("recoveryEncryptedChallenge");

    if (!storedEmail || !storedSessionId || !storedChallenge) {
      console.log("[VerifyRecovery] No active recovery session, redirecting");
      navigate("/recovery/initiate");
      return;
    }

    setEmail(storedEmail);
    setSessionId(storedSessionId);
    setEncryptedChallenge(storedChallenge);
  }, [navigate]);

  // Count words in recovery phrase
  const wordCount = useMemo(() => {
    if (!recoveryPhrase.trim()) return 0;
    return recoveryPhrase.trim().split(/\s+/).length;
  }, [recoveryPhrase]);

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

    try {
      // Validate recovery phrase
      const words = recoveryPhrase.trim().toLowerCase().split(/\s+/);
      if (words.length !== 12) {
        throw new Error("Recovery phrase must be exactly 12 words");
      }

      // Join words with single space (normalize)
      const normalizedPhrase = words.join(" ");

      console.log("[VerifyRecovery] Decrypting challenge with recovery phrase");

      // Decrypt the challenge using recovery phrase via backend
      const decryptResult = await DecryptRecoveryChallenge({
        recoveryMnemonic: normalizedPhrase,
        encryptedChallenge: encryptedChallenge,
      });

      setDecrypting(false);

      if (!decryptResult.isValid) {
        throw new Error("Invalid recovery phrase");
      }

      console.log("[VerifyRecovery] Challenge decrypted, verifying with server");

      // Verify the decrypted challenge with the server
      const response = await VerifyRecoveryAPI(
        sessionId,
        decryptResult.decryptedChallenge
      );

      console.log("[VerifyRecovery] Recovery verified successfully");

      // Store recovery token for the completion step
      sessionStorage.setItem("recoveryToken", response.recoveryToken);
      sessionStorage.setItem("canResetCredentials", response.canResetCredentials.toString());

      // Clear the recovery phrase from memory
      setRecoveryPhrase("");

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

  const handlePaste = async () => {
    try {
      const text = await navigator.clipboard.readText();
      setRecoveryPhrase(text.trim());
      setCopied(true);
      setTimeout(() => setCopied(false), 3000);
    } catch (err) {
      console.error("Failed to read clipboard:", err);
      alert("Failed to paste from clipboard. Please paste manually.");
    }
  };

  const handleStartOver = () => {
    // Clear session data and go back to initiate
    sessionStorage.removeItem("recoveryEmail");
    sessionStorage.removeItem("recoverySessionId");
    sessionStorage.removeItem("recoveryEncryptedChallenge");
    setRecoveryPhrase("");
    navigate("/recovery/initiate");
  };

  if (!email) {
    return (
      <Page title="Verify Recovery" showBackButton={true}>
        <p>Loading recovery session...</p>
      </Page>
    );
  }

  return (
    <Page title="Verify Your Recovery Phrase" showBackButton={false}>
      <div style={{ maxWidth: "600px" }}>
        {/* Progress Indicator */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            marginBottom: "20px",
            gap: "10px",
          }}
        >
          <div
            style={{
              width: "30px",
              height: "30px",
              borderRadius: "50%",
              background: "#27ae60",
              color: "white",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "14px",
              fontWeight: "bold",
            }}
          >
            ✓
          </div>
          <span style={{ color: "#27ae60", fontWeight: "bold" }}>Email</span>
          <div style={{ width: "30px", height: "2px", background: "#27ae60" }} />
          <div
            style={{
              width: "30px",
              height: "30px",
              borderRadius: "50%",
              background: "#3498db",
              color: "white",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "14px",
              fontWeight: "bold",
            }}
          >
            2
          </div>
          <span style={{ color: "#333", fontWeight: "bold" }}>Verify</span>
          <div style={{ width: "30px", height: "2px", background: "#ccc" }} />
          <div
            style={{
              width: "30px",
              height: "30px",
              borderRadius: "50%",
              background: "#ccc",
              color: "#666",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "14px",
              fontWeight: "bold",
            }}
          >
            3
          </div>
          <span style={{ color: "#666" }}>Reset</span>
        </div>

        <p style={{ marginBottom: "20px", color: "#333" }}>
          Enter your 12-word recovery phrase for <strong>{email}</strong>
        </p>

        {/* Error Message */}
        {error && (
          <div
            style={{
              background: "#f8d7da",
              border: "1px solid #f5c6cb",
              borderRadius: "8px",
              padding: "15px",
              marginBottom: "20px",
              color: "#721c24",
            }}
          >
            <strong>Verification Error:</strong> {error}
          </div>
        )}

        {/* Decrypting Message */}
        {decrypting && (
          <div
            style={{
              background: "#cce5ff",
              border: "1px solid #b8daff",
              borderRadius: "8px",
              padding: "15px",
              marginBottom: "20px",
              color: "#004085",
            }}
          >
            Decrypting challenge with your recovery key...
          </div>
        )}

        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: "15px" }}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: "5px",
              }}
            >
              <label
                htmlFor="recoveryPhrase"
                style={{ fontWeight: "bold", color: "#333" }}
              >
                Recovery Phrase
              </label>
              <span
                style={{
                  fontSize: "12px",
                  color:
                    wordCount === 12
                      ? "#27ae60"
                      : wordCount > 0
                        ? "#f39c12"
                        : "#666",
                  fontWeight: "bold",
                }}
              >
                {wordCount}/12 words
              </span>
            </div>
            <textarea
              id="recoveryPhrase"
              value={recoveryPhrase}
              onChange={(e) => setRecoveryPhrase(e.target.value)}
              placeholder="Enter your 12-word recovery phrase separated by spaces"
              rows={4}
              required
              disabled={loading}
              style={{
                width: "100%",
                padding: "12px",
                fontFamily: "monospace",
                fontSize: "14px",
                lineHeight: "1.6",
                borderRadius: "8px",
                border:
                  wordCount === 12 ? "2px solid #27ae60" : "1px solid #ccc",
                background: wordCount === 12 ? "#f0fff0" : "#fff",
                resize: "none",
                color: "#333",
              }}
            />
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginTop: "5px",
              }}
            >
              <small style={{ color: "#666" }}>
                Enter all 12 words in the correct order, separated by spaces
              </small>
              <button
                type="button"
                onClick={handlePaste}
                disabled={loading}
                style={{
                  padding: "4px 8px",
                  fontSize: "12px",
                  background: copied ? "#27ae60" : "#95a5a6",
                  color: "white",
                  border: "none",
                  borderRadius: "4px",
                  cursor: loading ? "not-allowed" : "pointer",
                }}
              >
                {copied ? "Pasted!" : "Paste"}
              </button>
            </div>
          </div>

          <div className="nav-buttons">
            <button
              type="submit"
              className="nav-button success"
              disabled={loading || wordCount !== 12}
              style={{
                opacity: wordCount === 12 ? 1 : 0.5,
                cursor: wordCount === 12 && !loading ? "pointer" : "not-allowed",
              }}
            >
              {loading
                ? decrypting
                  ? "Decrypting..."
                  : "Verifying..."
                : "Verify Recovery Phrase"}
            </button>
            <button
              type="button"
              onClick={handleStartOver}
              className="nav-button secondary"
              disabled={loading}
            >
              Start Over
            </button>
          </div>
        </form>

        {/* Security Tips */}
        <div
          style={{
            marginTop: "20px",
            padding: "15px",
            background: "#f0f0f0",
            borderRadius: "8px",
          }}
        >
          <strong>Security Tips:</strong>
          <ul style={{ margin: "10px 0 0", paddingLeft: "20px", color: "#333" }}>
            <li>Never share your recovery phrase with anyone</li>
            <li>Make sure no one is watching your screen</li>
            <li>Your phrase is validated locally and never sent in plain text</li>
          </ul>
        </div>
      </div>
    </Page>
  );
}

export default VerifyRecovery;
