// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Recovery/VerifyRecovery.jsx
// UIX version - Theme-aware Recovery Verification with UIX components
import React, { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate, Link } from "react-router";
import { useServices } from "../../../services/Services";
import { Button, Card, Alert, GDPRFooter, useUIXTheme } from "../../../components/UIX";
import {
  ArrowRightIcon,
  ArrowLeftIcon,
  LockClosedIcon,
  CheckIcon,
  KeyIcon,
  ClipboardDocumentIcon,
  DocumentTextIcon,
} from "@heroicons/react/24/outline";

const VerifyRecovery = () => {
  const navigate = useNavigate();
  const { recoveryManager } = useServices();
  const { getThemeClasses } = useUIXTheme();
  const [recoveryPhrase, setRecoveryPhrase] = useState("");
  const [loading, setLoading] = useState(false);
  const [decrypting, setDecrypting] = useState(false);
  const [error, setError] = useState("");
  const [email, setEmail] = useState("");
  const [pasted, setPasted] = useState(false);

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

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
      // Clear any pending timers
      if (pastedTimerRef.current) {
        clearTimeout(pastedTimerRef.current);
      }
      // Security: Explicitly clear sensitive data from memory
      setRecoveryPhrase("");
    };
  }, []);

  useEffect(() => {
    // Check if we have an active recovery session
    const recoveryEmail = recoveryManager.getRecoveryEmail();
    const hasSession = recoveryManager.hasActiveRecoverySession();

    if (!recoveryEmail || !hasSession) {
      if (import.meta.env.DEV) {
        console.log("[VerifyRecovery] No active recovery session, redirecting");
      }
      navigate("/recovery/initiate");
      return;
    }

    if (isMountedRef.current) {
      setEmail(recoveryEmail);
    }
  }, [navigate, recoveryManager]);

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

    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
      const normalizedPhrase = words.join(" ");

      if (import.meta.env.DEV) {
        console.log("[VerifyRecovery] Decrypting challenge with recovery phrase");
      }

      // Decrypt the challenge using recovery phrase
      const decryptedChallenge =
        await recoveryManager.decryptChallengeWithRecoveryPhrase(
          normalizedPhrase,
        );

      if (isMountedRef.current) {
        setDecrypting(false);
      }

      if (import.meta.env.DEV) {
        console.log("[VerifyRecovery] Challenge decrypted, verifying with server");
      }

      // Verify the decrypted challenge
      const response = await recoveryManager.verifyRecovery(decryptedChallenge);

      if (import.meta.env.DEV) {
        console.log("[VerifyRecovery] Recovery verified successfully");
      }

      // Security: Clear sensitive data from memory before navigation
      if (isMountedRef.current) {
        setRecoveryPhrase("");
      }

      // Navigate to completion step
      navigate("/recovery/complete");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("[VerifyRecovery] Recovery verification failed:", error);
      }
      if (isMountedRef.current) {
        setError(error.message);
        setDecrypting(false);
      }
    } finally {
      if (isMountedRef.current) {
        setLoading(false);
      }
    }
  }, [recoveryPhrase, recoveryManager, navigate]);

  const handleBackToInitiate = useCallback(() => {
    // Security: Clear sensitive data from memory before navigation
    setRecoveryPhrase("");
    recoveryManager.clearRecoverySession();
    navigate("/recovery/initiate");
  }, [recoveryManager, navigate]);

  const handlePasteRecoveryPhrase = useCallback(async () => {
    try {
      const text = await navigator.clipboard.readText();
      if (isMountedRef.current) {
        setRecoveryPhrase(text.trim());
        setPasted(true);

        // Clear any existing timer
        if (pastedTimerRef.current) {
          clearTimeout(pastedTimerRef.current);
        }

        // Set new timer
        pastedTimerRef.current = setTimeout(() => {
          if (isMountedRef.current) {
            setPasted(false);
          }
          pastedTimerRef.current = null;
        }, 3000);
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to read clipboard:", error);
      }
      alert("Failed to paste from clipboard. Please paste manually.");
    }
  }, []);

  if (!email) {
    return (
      <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")} flex items-center justify-center`}>
        <div className="text-center">
          <h2 className={`text-2xl font-bold ${getThemeClasses("text-primary")} mb-4`}>Loading...</h2>
          <p className={getThemeClasses("text-secondary")}>Checking recovery session...</p>
        </div>
      </div>
    );
  }

  // Count words in recovery phrase
  const wordCount = recoveryPhrase.trim()
    ? recoveryPhrase.trim().split(/\s+/).length
    : 0;

  return (
    <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")} flex flex-col`}>
      {/* Navigation */}
      <nav className={`${getThemeClasses("bg-card")}/95 backdrop-blur-sm border-b ${getThemeClasses("border-muted")}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-4">
            <Link to="/" className="flex items-center group">
              <div className={`flex items-center justify-center h-10 w-10 ${getThemeClasses("bg-gradient-secondary")} rounded-lg mr-3 group-hover:scale-105 transition-transform duration-200`}>
                <LockClosedIcon className="h-6 w-6 text-white" />
              </div>
              <span className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                MapleFile
              </span>
            </Link>
            <div className="flex items-center space-x-6">
              <span className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                Step 2 of 3
              </span>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <div className="flex-1 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-2xl w-full space-y-8">
          {/* Progress Indicator */}
          <div className="flex items-center justify-center mb-8">
            <div className="flex items-center space-x-4">
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("bg-success")} rounded-full text-white text-sm font-bold`}>
                  <CheckIcon className="h-4 w-4" />
                </div>
                <span className={`ml-2 text-sm font-semibold ${getThemeClasses("text-success")}`}>
                  Email
                </span>
              </div>
              <div className={`w-12 h-0.5 ${getThemeClasses("bg-success")}`}></div>
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("bg-gradient-secondary")} rounded-full text-white text-sm font-bold`}>
                  2
                </div>
                <span className={`ml-2 text-sm font-semibold ${getThemeClasses("text-primary")}`}>
                  Verify
                </span>
              </div>
              <div className={`w-12 h-0.5 ${getThemeClasses("step-inactive")}`}></div>
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("step-inactive")} rounded-full ${getThemeClasses("step-inactive-text")} text-sm font-bold`}>
                  3
                </div>
                <span className={`ml-2 text-sm ${getThemeClasses("step-inactive-text")}`}>Reset</span>
              </div>
            </div>
          </div>

          {/* Header */}
          <div className="text-center animate-fade-in-up">
            <div className="flex justify-center mb-6">
              <div className="relative">
                <div className={`flex items-center justify-center h-16 w-16 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl shadow-lg animate-pulse`}>
                  <DocumentTextIcon className="h-8 w-8 text-white" />
                </div>
                <div className={`absolute -inset-1 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl blur opacity-20 animate-pulse`}></div>
              </div>
            </div>
            <h2 className={`text-3xl font-black ${getThemeClasses("text-primary")} mb-2`}>
              Verify Your Recovery Phrase
            </h2>
            <p className={getThemeClasses("text-secondary")}>
              Enter your 12-word recovery phrase for {email}
            </p>
          </div>

          {/* Form Card */}
          <Card className="shadow-2xl animate-fade-in-up-delay">
            <div className="p-8">
              {/* Error Message */}
              {error && (
                <Alert type="error" className="mb-6 animate-fade-in">
                  <div>
                    <h3 className="text-sm font-semibold mb-1">
                      Verification Error
                    </h3>
                    <p className="text-sm">{error}</p>
                  </div>
                </Alert>
              )}

              {/* Decrypting Message */}
              {decrypting && (
                <Alert type="info" className="mb-6 animate-fade-in">
                  <div className="flex items-center">
                    <svg
                      className="animate-spin h-5 w-5 mr-3"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      ></path>
                    </svg>
                    <span className="text-sm">
                      Decrypting challenge with your recovery key...
                    </span>
                  </div>
                </Alert>
              )}

              {/* Form */}
              <form onSubmit={handleSubmit} className="space-y-6">
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label
                      htmlFor="recoveryPhrase"
                      className={`block text-sm font-semibold ${getThemeClasses("text-primary")}`}
                    >
                      Recovery Phrase
                    </label>
                    <span
                      className={`text-xs font-medium ${
                        wordCount === 12
                          ? getThemeClasses("text-success")
                          : wordCount > 0
                            ? getThemeClasses("text-warning")
                            : getThemeClasses("text-secondary")
                      }`}
                    >
                      {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}
                    className={`w-full px-4 py-3 border-2 rounded-xl focus:ring-2 ${getThemeClasses("focus:ring-accent")} ${getThemeClasses("focus:border-accent")} transition-all duration-200 ${getThemeClasses("bg-card")} disabled:opacity-50 disabled:cursor-not-allowed ${getThemeClasses("text-primary")} ${getThemeClasses("placeholder-secondary")} font-mono text-sm leading-relaxed resize-none ${
                      wordCount === 12
                        ? `${getThemeClasses("border-success")} ${getThemeClasses("bg-success-light")}`
                        : getThemeClasses("border-muted")
                    }`}
                  />
                  <div className="mt-2 flex items-center justify-between">
                    <p className={`text-xs ${getThemeClasses("text-secondary")}`}>
                      Enter all 12 words in the correct order, separated by spaces
                    </p>
                    <Button
                      type="button"
                      onClick={handlePasteRecoveryPhrase}
                      disabled={loading}
                      variant={pasted ? "success" : "secondary"}
                      size="sm"
                    >
                      {pasted ? (
                        <span className="flex items-center whitespace-nowrap">
                          <CheckIcon className="h-3 w-3 mr-1 flex-shrink-0" />
                          Pasted!
                        </span>
                      ) : (
                        <span className="flex items-center whitespace-nowrap">
                          <ClipboardDocumentIcon className="h-3 w-3 mr-1 flex-shrink-0" />
                          Paste
                        </span>
                      )}
                    </Button>
                  </div>
                </div>

                <div className="space-y-3">
                  <Button
                    type="submit"
                    disabled={loading || wordCount !== 12}
                    variant="primary"
                    size="lg"
                    fullWidth
                    loading={loading}
                    loadingText={decrypting ? "Decrypting..." : "Verifying..."}
                    className="group shadow-lg hover:shadow-xl transform hover:scale-105"
                  >
                    <span className="flex items-center">
                      <KeyIcon className="mr-2 h-4 w-4" />
                      Verify Recovery Phrase
                      <ArrowRightIcon className="ml-2 h-4 w-4 group-hover:translate-x-1 transition-transform duration-200" />
                    </span>
                  </Button>

                  <Button
                    type="button"
                    onClick={handleBackToInitiate}
                    disabled={loading}
                    variant="secondary"
                    size="md"
                    fullWidth
                  >
                    <span className="flex items-center justify-center whitespace-nowrap">
                      <ArrowLeftIcon className="mr-2 h-4 w-4 flex-shrink-0" />
                      Start Over
                    </span>
                  </Button>
                </div>
              </form>
            </div>
          </Card>

        </div>
      </div>

      {/* Footer */}
      <GDPRFooter containerClassName="bg-white/75" />

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

        @keyframes fade-in-up {
          from {
            opacity: 0;
            transform: translateY(30px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

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

        .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>
    </div>
  );
};

export default VerifyRecovery;
