// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Register/RecoveryCode.jsx
// UIX version - Recovery Phrase Display (100% UIX Components)
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useNavigate } from "react-router";
import {
  Card,
  Button,
  Checkbox,
  Alert,
  GDPRFooter,
  Navigation,
  PageContainer,
  PageHeader,
  ProgressIndicator,
  WordGrid,
} from "../../../components/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  LockClosedIcon,
  CheckIcon,
  ExclamationTriangleIcon,
  KeyIcon,
  ClipboardDocumentIcon,
  PrinterIcon,
  ExclamationCircleIcon,
  BookmarkIcon,
} from "@heroicons/react/24/outline";

const RecoveryCode = () => {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Refs for cleanup
  const isMountedRef = useRef(true);
  const copyTimeoutRef = useRef(null);

  const [recoveryMnemonic, setRecoveryMnemonic] = useState("");
  const [email, setEmail] = useState("");
  const [savedRecoveryCode, setSavedRecoveryCode] = useState(false);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    isMountedRef.current = true;

    // Get registration result from sessionStorage
    const registrationResult = sessionStorage.getItem("registrationResult");
    const registeredEmail = sessionStorage.getItem("registeredEmail");

    if (!registrationResult || !registeredEmail) {
      // Redirect back to registration if no data found
      if (import.meta.env.DEV) {
        console.log("[RecoveryCode] No registration data found, redirecting to register");
      }
      navigate("/register");
      return;
    }

    try {
      const result = JSON.parse(registrationResult);
      if (import.meta.env.DEV) {
        console.log("[RecoveryCode] Registration result loaded");
      }

      // Get the recovery mnemonic that was generated on the frontend
      const mnemonic = result.recoveryMnemonic;

      // Validate mnemonic format - should be a string with words separated by spaces
      if (!mnemonic || typeof mnemonic !== 'string') {
        if (import.meta.env.DEV) {
          console.error("[RecoveryCode] Invalid or missing recovery mnemonic");
        }
        navigate("/register");
        return;
      }

      // Validate mnemonic contains only alphanumeric words and spaces
      // This prevents XSS attempts via sessionStorage manipulation
      const words = mnemonic.trim().split(/\s+/);
      const isValidMnemonic = words.length >= 12 &&
        words.every(word => /^[a-zA-Z0-9]+$/.test(word));

      if (!isValidMnemonic) {
        if (import.meta.env.DEV) {
          console.error("[RecoveryCode] Mnemonic failed validation - invalid format or characters");
        }
        // Clear potentially malicious data
        sessionStorage.removeItem("registrationResult");
        sessionStorage.removeItem("registeredEmail");
        navigate("/register");
        return;
      }

      // Validate email format
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(registeredEmail)) {
        if (import.meta.env.DEV) {
          console.error("[RecoveryCode] Invalid email format");
        }
        sessionStorage.removeItem("registrationResult");
        sessionStorage.removeItem("registeredEmail");
        navigate("/register");
        return;
      }

      if (isMountedRef.current) {
        setRecoveryMnemonic(mnemonic);
        setEmail(registeredEmail);
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[RecoveryCode] Error parsing registration result:", error);
      }
      // Clear potentially corrupted data
      sessionStorage.removeItem("registrationResult");
      sessionStorage.removeItem("registeredEmail");
      navigate("/register");
    }

    return () => {
      isMountedRef.current = false;
      if (copyTimeoutRef.current) {
        clearTimeout(copyTimeoutRef.current);
      }
    };
  }, [navigate]);

  const handleContinue = useCallback(() => {
    if (!savedRecoveryCode) {
      alert(
        "Please confirm that you have saved your recovery code before continuing!",
      );
      return;
    }

    // Navigate to email verification
    navigate("/register/verify-email");
  }, [savedRecoveryCode, navigate]);

  const handleBackToRegistration = useCallback(() => {
    // Clear session storage
    sessionStorage.removeItem("registrationResult");
    sessionStorage.removeItem("registeredEmail");
    navigate("/register");
  }, [navigate]);

  const handleCopyToClipboard = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(recoveryMnemonic);
      if (isMountedRef.current) {
        setCopied(true);
        copyTimeoutRef.current = setTimeout(() => {
          if (isMountedRef.current) {
            setCopied(false);
          }
        }, 3000);
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[RecoveryCode] Failed to copy to clipboard:", error);
      }
      // 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);
      if (isMountedRef.current) {
        setCopied(true);
        copyTimeoutRef.current = setTimeout(() => {
          if (isMountedRef.current) {
            setCopied(false);
          }
        }, 3000);
      }
    }
  }, [recoveryMnemonic]);

  const handlePrint = useCallback(() => {
    const printWindow = window.open("", "_blank");
    if (!printWindow) {
      // Popup blocked - fall back to alert
      alert("Please allow popups to print your recovery phrase.");
      return;
    }

    const doc = printWindow.document;

    // Build document using safe DOM manipulation (no document.write)
    // Create style element
    const style = doc.createElement("style");
    style.textContent = `
      body {
        font-family: Arial, sans-serif;
        padding: 20px;
        line-height: 1.6;
      }
      .header {
        text-align: center;
        margin-bottom: 30px;
      }
      .warning {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        padding: 15px;
        margin: 20px 0;
        border-radius: 4px;
      }
      .mnemonic {
        background: #f8f9fa;
        border: 2px solid #dee2e6;
        padding: 20px;
        margin: 20px 0;
        border-radius: 4px;
        font-family: monospace;
        font-size: 16px;
        text-align: center;
        line-height: 2;
      }
      .word {
        display: inline-block;
        margin: 5px;
        padding: 5px 10px;
        background: white;
        border: 1px solid #ccc;
        border-radius: 3px;
      }
      .footer {
        margin-top: 30px;
        font-size: 12px;
        color: #666;
      }
      .privacy-notice {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #ddd;
      }
      .privacy-text {
        font-size: 10px;
        color: #666;
      }
    `;
    doc.head.appendChild(style);

    // Set title safely
    doc.title = "MapleFile Recovery Phrase";

    // Build body content using textContent for user data (XSS-safe)
    const body = doc.body;

    // Header section
    const header = doc.createElement("div");
    header.className = "header";

    const h1 = doc.createElement("h1");
    h1.textContent = "MapleFile Recovery Phrase";
    header.appendChild(h1);

    const accountP = doc.createElement("p");
    const accountStrong = doc.createElement("strong");
    accountStrong.textContent = "Account: ";
    accountP.appendChild(accountStrong);
    accountP.appendChild(doc.createTextNode(email)); // Safe: textContent equivalent
    header.appendChild(accountP);

    const dateP = doc.createElement("p");
    const dateStrong = doc.createElement("strong");
    dateStrong.textContent = "Generated: ";
    dateP.appendChild(dateStrong);
    dateP.appendChild(doc.createTextNode(new Date().toLocaleString()));
    header.appendChild(dateP);

    body.appendChild(header);

    // Warning section
    const warning = doc.createElement("div");
    warning.className = "warning";
    const warningH3 = doc.createElement("h3");
    warningH3.textContent = "⚠️ IMPORTANT SECURITY NOTICE";
    warning.appendChild(warningH3);
    const warningP = doc.createElement("p");
    warningP.textContent = "This recovery phrase is the ONLY way to recover your account if you forget your password. Keep it safe and never share it with anyone.";
    warning.appendChild(warningP);
    body.appendChild(warning);

    // Mnemonic words section
    const mnemonic = doc.createElement("div");
    mnemonic.className = "mnemonic";
    recoveryMnemonic.split(" ").forEach((word, index) => {
      const wordSpan = doc.createElement("span");
      wordSpan.className = "word";
      wordSpan.textContent = `${index + 1}. ${word}`; // Safe: textContent
      mnemonic.appendChild(wordSpan);
    });
    body.appendChild(mnemonic);

    // Footer section
    const footer = doc.createElement("div");
    footer.className = "footer";

    const tipsP = doc.createElement("p");
    const tipsStrong = doc.createElement("strong");
    tipsStrong.textContent = "Security Tips:";
    tipsP.appendChild(tipsStrong);
    footer.appendChild(tipsP);

    const tipsList = doc.createElement("ul");
    const tips = [
      "Store this phrase in a secure location (safe, safety deposit box)",
      "Consider making multiple copies and storing them separately",
      "Never store this digitally (computer files, cloud storage, photos)",
      "Never share this phrase with anyone, including MapleFile support",
      "Write clearly and double-check each word"
    ];
    tips.forEach((tip) => {
      const li = doc.createElement("li");
      li.textContent = tip;
      tipsList.appendChild(li);
    });
    footer.appendChild(tipsList);

    // Privacy notice
    const privacyDiv = doc.createElement("div");
    privacyDiv.className = "privacy-notice";

    const privacyTitleP = doc.createElement("p");
    const privacyStrong = doc.createElement("strong");
    privacyStrong.textContent = "Privacy Notice:";
    privacyTitleP.appendChild(privacyStrong);
    privacyDiv.appendChild(privacyTitleP);

    const privacyTextP = doc.createElement("p");
    privacyTextP.className = "privacy-text";
    privacyTextP.textContent = "This recovery phrase is your personal cryptographic data. Data Controller: Maple Open Tech Inc. (Canada). Your GDPR rights: Access, rectification, erasure, restriction, portability, objection, and complaint to supervisory authority. Contact: privacy@mapleopentech.ca | This document was generated locally and contains no tracking.";
    privacyDiv.appendChild(privacyTextP);

    footer.appendChild(privacyDiv);
    body.appendChild(footer);

    doc.close();

    // Track if print has been triggered to prevent double printing
    let printTriggered = false;

    const triggerPrint = () => {
      if (printTriggered || printWindow.closed) return;
      printTriggered = true;

      printWindow.focus();

      // Close window after print dialog is dismissed (print or cancel)
      printWindow.onafterprint = () => {
        printWindow.close();
      };

      printWindow.print();

      // Fallback: close after delay if onafterprint isn't supported
      setTimeout(() => {
        if (!printWindow.closed) {
          printWindow.close();
        }
      }, 500);
    };

    // Trigger print once content is ready
    if (printWindow.document.readyState === 'complete') {
      triggerPrint();
    } else {
      printWindow.onload = triggerPrint;
      // Fallback timeout in case onload doesn't fire
      setTimeout(triggerPrint, 250);
    }
  }, [email, recoveryMnemonic]);

  const handleCheckboxChange = useCallback((checked) => {
    setSavedRecoveryCode(checked);
  }, []);

  // Memoize progress steps
  const progressSteps = useMemo(
    () => [
      { label: "Register", completed: true },
      { label: "Recovery", completed: false },
      { label: "Verify", completed: false },
    ],
    [],
  );

  // Memoize navigation links
  const navLinks = useMemo(
    () => [{ to: "/login", text: "Step 2 of 3", variant: "secondary" }],
    [],
  );

  if (!recoveryMnemonic) {
    return (
      <PageContainer>
        <Card className="text-center p-8 max-w-md mx-auto mt-20">
          <h2 className={`text-2xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
            Loading...
          </h2>
          <p className={getThemeClasses("text-secondary")}>
            Loading your recovery phrase...
          </p>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer showBlobs>
      {/* Navigation */}
      <Navigation icon={LockClosedIcon} logoText="MapleFile" links={navLinks} />

      {/* Main Content */}
      <div className="flex-1 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 relative z-10">
        <div className="max-w-2xl w-full space-y-8">
          {/* Progress Indicator */}
          <ProgressIndicator steps={progressSteps} currentStep={2} />

          {/* Page Header */}
          <PageHeader
            icon={KeyIcon}
            title="Save Your Recovery Phrase"
            subtitle="Write down these 12 words in the exact order shown"
            className="text-center"
          />

          {/* Warning Alert */}
          <div className={`flex items-center justify-center space-x-2 text-sm ${getThemeClasses("text-secondary")}`}>
            <ExclamationCircleIcon className={`h-4 w-4 ${getThemeClasses("icon-warning")}`} />
            <span className={`${getThemeClasses("text-warning")} font-semibold`}>
              This is your ONLY way to recover your account
            </span>
          </div>

          {/* GDPR Notice */}
          <Alert type="info">
            <p className="text-xs">
              Your recovery phrase is generated locally in your browser for account recovery (legal basis: contract); never transmitted to servers; automatically cleared after registration or when you close this page.
            </p>
          </Alert>

          {/* Warning Card */}
          <Alert type="warning" className="animate-fade-in-up-delay">
            <div>
              <h3 className="text-lg font-semibold mb-2">
                Critical Security Notice
              </h3>
              <ul className="text-sm space-y-1">
                <li className="flex items-start">
                  <span className="mr-2">•</span>
                  This recovery phrase is the <strong>only way</strong> to
                  recover your account
                </li>
                <li className="flex items-start">
                  <span className="mr-2">•</span>
                  We cannot recover your account without it
                </li>
                <li className="flex items-start">
                  <span className="mr-2">•</span>
                  Never share this phrase with anyone, including MapleFile
                  support
                </li>
                <li className="flex items-start">
                  <span className="mr-2">•</span>
                  Store it in a secure physical location
                </li>
              </ul>
            </div>
          </Alert>

          {/* Recovery Phrase Card */}
          <Card className="shadow-2xl animate-fade-in-up-delay-2">
            <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-6 flex items-center justify-center`}>
              <BookmarkIcon className="h-5 w-5 mr-2" />
              Your 12-Word Recovery Phrase
            </h3>

            {/* Word Grid Component */}
            <WordGrid words={recoveryMnemonic} columns={3} className="mb-8" />

            {/* Action Buttons */}
            <div className="flex flex-col sm:flex-row gap-3 mb-8">
              <Button
                type="button"
                onClick={handleCopyToClipboard}
                variant={copied ? "success" : "secondary"}
                fullWidth
              >
                {copied ? (
                  <>
                    <CheckIcon className="h-5 w-5 mr-2" />
                    Copied to Clipboard!
                  </>
                ) : (
                  <>
                    <ClipboardDocumentIcon className="h-5 w-5 mr-2" />
                    Copy to Clipboard
                  </>
                )}
              </Button>
              <Button
                type="button"
                onClick={handlePrint}
                variant="secondary"
                fullWidth
              >
                <PrinterIcon className="h-5 w-5 mr-2" />
                Print Recovery Phrase
              </Button>
            </div>

            {/* Confirmation Checkbox */}
            <Card padding="p-4">
              <Checkbox
                label="I have written down my recovery phrase and stored it securely"
                checked={savedRecoveryCode}
                onChange={handleCheckboxChange}
              />
              <p className={`text-xs ${getThemeClasses("text-secondary")} mt-1 ml-7`}>
                Please confirm you've saved your recovery phrase before
                continuing
              </p>
            </Card>
          </Card>

          {/* Security Tips */}
          <Card className="animate-fade-in-up-delay-3">
            <h3 className={`text-sm font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center`}>
              <ExclamationCircleIcon className="h-4 w-4 mr-2" />
              Security Best Practices
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
              <div>
                <h4 className={`font-semibold ${getThemeClasses("text-success")} mb-2`}>✅ DO:</h4>
                <ul className={`space-y-1 ${getThemeClasses("text-secondary")}`}>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-success")} mr-2`}>•</span>
                    Write it on paper with a pen
                  </li>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-success")} mr-2`}>•</span>
                    Store in a safe or safety deposit box
                  </li>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-success")} mr-2`}>•</span>
                    Make multiple physical copies
                  </li>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-success")} mr-2`}>•</span>
                    Store copies in separate locations
                  </li>
                </ul>
              </div>
              <div>
                <h4 className={`font-semibold ${getThemeClasses("text-error")} mb-2`}>❌ DON'T:</h4>
                <ul className={`space-y-1 ${getThemeClasses("text-secondary")}`}>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                    Take a screenshot or photo
                  </li>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                    Save in a computer file
                  </li>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                    Store in cloud storage
                  </li>
                  <li className="flex items-start">
                    <span className={`${getThemeClasses("text-error")} mr-2`}>•</span>
                    Share via email or messages
                  </li>
                </ul>
              </div>
            </div>
          </Card>

          {/* Next Steps */}
          <Alert type="info" className="animate-fade-in-up-delay-3">
            <div>
              <h3 className="text-sm font-semibold mb-3">
                What happens next?
              </h3>
              <ol className="text-sm space-y-2">
                <li className="flex items-start">
                  <span className="font-semibold mr-2">1.</span>
                  Write down your recovery phrase on paper
                </li>
                <li className="flex items-start">
                  <span className="font-semibold mr-2">2.</span>
                  Check your email ({email}) for a verification code
                </li>
                <li className="flex items-start">
                  <span className="font-semibold mr-2">3.</span>
                  Enter the code to complete registration
                </li>
                <li className="flex items-start">
                  <span className="font-semibold mr-2">4.</span>
                  Start using MapleFile with end-to-end encryption
                </li>
              </ol>
            </div>
          </Alert>

          {/* Action Buttons */}
          <div className="flex flex-col sm:flex-row gap-4 animate-fade-in-up-delay-3">
            <Button
              type="button"
              onClick={handleBackToRegistration}
              variant="secondary"
              fullWidth
            >
              Back to Registration
            </Button>

            <Button
              type="button"
              onClick={handleContinue}
              disabled={!savedRecoveryCode}
              variant="primary"
              fullWidth
            >
              Continue to Email Verification
            </Button>
          </div>
        </div>
      </div>

      {/* Footer */}
      <GDPRFooter />

      {/* CSS Animations */}
      <style>{`
        @keyframes fade-in-up {
          from {
            opacity: 0;
            transform: translateY(30px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        .animate-fade-in-up {
          animation: fade-in-up 0.6s ease-out;
        }

        .animate-fade-in-up-delay {
          animation: fade-in-up 0.6s ease-out 0.2s both;
        }

        .animate-fade-in-up-delay-2 {
          animation: fade-in-up 0.6s ease-out 0.4s both;
        }

        .animate-fade-in-up-delay-3 {
          animation: fade-in-up 0.6s ease-out 0.6s both;
        }
      `}</style>
    </PageContainer>
  );
};

export default RecoveryCode;
