// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/Anonymous/Register/RecoveryCode.jsx
import { useState, useEffect, useMemo } from "react";
import { Link, useNavigate } from "react-router-dom";
import Page from "../../../components/Page";

function RecoveryCode() {
  const navigate = useNavigate();
  const [recoveryMnemonic, setRecoveryMnemonic] = useState("");
  const [email, setEmail] = useState("");
  const [copied, setCopied] = useState(false);
  const [confirmed, setConfirmed] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    // Get recovery mnemonic from sessionStorage
    const storedMnemonic = sessionStorage.getItem("recoveryMnemonic");
    const storedEmail = sessionStorage.getItem("registrationEmail");

    if (!storedMnemonic) {
      setError("No recovery code found. Please start registration again.");
      return;
    }

    setRecoveryMnemonic(storedMnemonic);
    setEmail(storedEmail || "");
  }, []);

  // Split mnemonic into words for display
  const mnemonicWords = useMemo(() => {
    if (!recoveryMnemonic) return [];
    return recoveryMnemonic.split(" ");
  }, [recoveryMnemonic]);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(recoveryMnemonic);
      setCopied(true);
      setTimeout(() => setCopied(false), 3000);
    } catch (err) {
      // Fallback for older browsers
      const textArea = document.createElement("textarea");
      textArea.value = recoveryMnemonic;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      setCopied(true);
      setTimeout(() => setCopied(false), 3000);
    }
  };

  const handleContinue = () => {
    if (!confirmed) {
      setError("Please confirm that you have saved your recovery code.");
      return;
    }

    // Clear the recovery mnemonic from sessionStorage
    sessionStorage.removeItem("recoveryMnemonic");

    // Navigate to email verification
    navigate(`/register/verify-email?email=${encodeURIComponent(email)}`);
  };

  if (error && !recoveryMnemonic) {
    return (
      <Page title="Recovery Code" showBackButton={true}>
        <p style={{ color: "red", marginBottom: "20px" }}>{error}</p>
        <div className="nav-buttons">
          <Link to="/register" className="nav-button">
            Start Registration
          </Link>
        </div>
      </Page>
    );
  }

  return (
    <Page title="Save Your Recovery Code" showBackButton={false}>
      <div style={{ maxWidth: "600px" }}>
        {/* Warning Banner */}
        <div
          style={{
            background: "#fff3cd",
            border: "1px solid #ffc107",
            borderRadius: "8px",
            padding: "15px",
            marginBottom: "20px",
          }}
        >
          <strong style={{ color: "#856404" }}>
            IMPORTANT: Save This Recovery Code!
          </strong>
          <p style={{ margin: "10px 0 0", color: "#856404", fontSize: "14px" }}>
            This 12-word recovery phrase is the ONLY way to recover your account
            if you forget your password. Write it down and store it in a safe
            place. You will NOT see this again.
          </p>
        </div>

        {/* Recovery Words Grid */}
        <div
          style={{
            background: "#f8f9fa",
            border: "2px solid #28a745",
            borderRadius: "8px",
            padding: "20px",
            marginBottom: "20px",
          }}
        >
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: "10px",
            }}
          >
            {mnemonicWords.map((word, index) => (
              <div
                key={index}
                style={{
                  background: "white",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  padding: "8px 12px",
                  fontFamily: "monospace",
                  fontSize: "14px",
                }}
              >
                <span style={{ color: "#666", marginRight: "8px" }}>
                  {index + 1}.
                </span>
                <span style={{ fontWeight: "bold" }}>{word}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Copy Button */}
        <button
          onClick={handleCopy}
          style={{
            width: "100%",
            padding: "12px",
            marginBottom: "20px",
            background: copied ? "#28a745" : "#007bff",
            color: "white",
            border: "none",
            borderRadius: "4px",
            cursor: "pointer",
            fontSize: "16px",
          }}
        >
          {copied ? "Copied to Clipboard!" : "Copy Recovery Code"}
        </button>

        {/* Security Tips */}
        <div
          style={{
            background: "#f0f0f0",
            borderRadius: "8px",
            padding: "15px",
            marginBottom: "20px",
          }}
        >
          <strong>Security Tips:</strong>
          <ul style={{ margin: "10px 0 0", paddingLeft: "20px" }}>
            <li>Write down these 12 words on paper</li>
            <li>Store in a secure location (safe, lockbox)</li>
            <li>Never share with anyone, including support staff</li>
            <li>Do not store digitally (screenshots, cloud storage)</li>
            <li>Consider storing copies in multiple secure locations</li>
          </ul>
        </div>

        {/* Confirmation Checkbox */}
        <label
          style={{
            display: "flex",
            alignItems: "flex-start",
            cursor: "pointer",
            marginBottom: "20px",
            padding: "10px",
            background: confirmed ? "#d4edda" : "#fff",
            border: confirmed ? "1px solid #28a745" : "1px solid #ddd",
            borderRadius: "4px",
          }}
        >
          <input
            type="checkbox"
            checked={confirmed}
            onChange={(e) => {
              setConfirmed(e.target.checked);
              setError("");
            }}
            style={{ marginRight: "10px", marginTop: "3px" }}
          />
          <span>
            I have written down my recovery code and stored it in a safe place.
            I understand that without this code, I cannot recover my account if
            I forget my password.
          </span>
        </label>

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

        {/* Continue Button */}
        <div className="nav-buttons">
          <button
            onClick={handleContinue}
            className="nav-button success"
            disabled={!confirmed}
            style={{
              opacity: confirmed ? 1 : 0.5,
              cursor: confirmed ? "pointer" : "not-allowed",
            }}
          >
            Continue to Email Verification
          </button>
        </div>

        {/* Email reminder */}
        {email && (
          <p
            style={{
              marginTop: "15px",
              color: "#666",
              fontSize: "14px",
              textAlign: "center",
            }}
          >
            Verification email will be sent to: <strong>{email}</strong>
          </p>
        )}
      </div>
    </Page>
  );
}

export default RecoveryCode;
