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

function CompleteRecovery() {
  const navigate = useNavigate();
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [recoveryPhrase, setRecoveryPhrase] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [email, setEmail] = useState("");
  const [recoveryToken, setRecoveryToken] = useState("");
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  useEffect(() => {
    // Get recovery session data from sessionStorage
    const storedEmail = sessionStorage.getItem("recoveryEmail");
    const storedToken = sessionStorage.getItem("recoveryToken");
    const canReset = sessionStorage.getItem("canResetCredentials");

    if (!storedEmail || !storedToken || canReset !== "true") {
      console.log("[CompleteRecovery] No verified recovery session, redirecting");
      navigate("/recovery/initiate");
      return;
    }

    setEmail(storedEmail);
    setRecoveryToken(storedToken);
  }, [navigate]);

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

  // Check if passwords match
  const passwordsMatch = newPassword && confirmPassword && newPassword === confirmPassword;

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

    try {
      // Validate passwords
      if (!newPassword) {
        throw new Error("Password is required");
      }

      if (newPassword.length < 8) {
        throw new Error("Password must be at least 8 characters long");
      }

      if (newPassword !== confirmPassword) {
        throw new Error("Passwords do not match");
      }

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

      // Normalize recovery phrase
      const normalizedPhrase = words.join(" ");

      console.log("[CompleteRecovery] Completing recovery with new password");

      // Call backend to complete recovery
      const response = await CompleteRecoveryAPI({
        recoveryToken: recoveryToken,
        recoveryMnemonic: normalizedPhrase,
        newPassword: newPassword,
      });

      console.log("[CompleteRecovery] Recovery completed successfully");

      // Clear all recovery session data
      sessionStorage.removeItem("recoveryEmail");
      sessionStorage.removeItem("recoverySessionId");
      sessionStorage.removeItem("recoveryEncryptedChallenge");
      sessionStorage.removeItem("recoveryToken");
      sessionStorage.removeItem("canResetCredentials");

      // Clear sensitive data from state
      setRecoveryPhrase("");
      setNewPassword("");
      setConfirmPassword("");

      // Show success and redirect to login
      alert("Account recovery completed successfully! You can now log in with your new password.");
      navigate("/login");
    } catch (err) {
      console.error("[CompleteRecovery] Recovery completion failed:", err);
      setError(err.message || "Failed to complete recovery");
    } finally {
      setLoading(false);
    }
  };

  const handleBackToVerify = () => {
    // Clear token but keep session
    sessionStorage.removeItem("recoveryToken");
    sessionStorage.removeItem("canResetCredentials");
    setRecoveryPhrase("");
    navigate("/recovery/verify");
  };

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

  return (
    <Page title="Set Your New Password" 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: "#27ae60",
              color: "white",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "14px",
              fontWeight: "bold",
            }}
          >
            ✓
          </div>
          <span style={{ color: "#27ae60", fontWeight: "bold" }}>Verify</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",
            }}
          >
            3
          </div>
          <span style={{ color: "#333", fontWeight: "bold" }}>Reset</span>
        </div>

        <p style={{ marginBottom: "20px", color: "#333" }}>
          Final step: Create a new password 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>Error:</strong> {error}
          </div>
        )}

        {/* Security Notice */}
        <div
          style={{
            background: "#cce5ff",
            border: "1px solid #b8daff",
            borderRadius: "8px",
            padding: "15px",
            marginBottom: "20px",
          }}
        >
          <strong style={{ color: "#004085" }}>Why enter your recovery phrase again?</strong>
          <p style={{ margin: "10px 0 0", color: "#004085", fontSize: "14px" }}>
            We need your recovery phrase to decrypt your master key and re-encrypt
            it with your new password. This ensures continuous access to your
            encrypted files.
          </p>
        </div>

        <form onSubmit={handleSubmit}>
          {/* Recovery Phrase */}
          <div style={{ marginBottom: "20px" }}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: "5px",
              }}
            >
              <label
                htmlFor="recoveryPhrase"
                style={{ fontWeight: "bold", color: "#333" }}
              >
                Recovery Phrase (Required Again)
              </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="Re-enter your 12-word recovery phrase"
              rows={3}
              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>

          {/* New Password Section */}
          <div
            style={{
              background: "#f0fff0",
              border: "1px solid #27ae60",
              borderRadius: "8px",
              padding: "15px",
              marginBottom: "20px",
            }}
          >
            <h3 style={{ margin: "0 0 15px 0", color: "#27ae60", fontSize: "16px" }}>
              Create Your New Password
            </h3>

            {/* New Password */}
            <div style={{ marginBottom: "15px" }}>
              <label
                htmlFor="newPassword"
                style={{
                  display: "block",
                  marginBottom: "5px",
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                New Password
              </label>
              <div style={{ position: "relative" }}>
                <input
                  type={showNewPassword ? "text" : "password"}
                  id="newPassword"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="Enter your new password"
                  required
                  disabled={loading}
                  minLength={8}
                  style={{
                    width: "100%",
                    padding: "8px",
                    paddingRight: "40px",
                    borderRadius: "4px",
                    border: "1px solid #ccc",
                    color: "#333",
                  }}
                />
                <button
                  type="button"
                  onClick={() => setShowNewPassword(!showNewPassword)}
                  style={{
                    position: "absolute",
                    right: "8px",
                    top: "50%",
                    transform: "translateY(-50%)",
                    background: "none",
                    border: "none",
                    cursor: "pointer",
                    color: "#666",
                    fontSize: "12px",
                  }}
                >
                  {showNewPassword ? "Hide" : "Show"}
                </button>
              </div>
              <small style={{ display: "block", marginTop: "5px", color: "#666" }}>
                Password must be at least 8 characters long
              </small>
            </div>

            {/* Confirm Password */}
            <div>
              <label
                htmlFor="confirmPassword"
                style={{
                  display: "block",
                  marginBottom: "5px",
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                Confirm New Password
              </label>
              <div style={{ position: "relative" }}>
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  id="confirmPassword"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="Confirm your new password"
                  required
                  disabled={loading}
                  style={{
                    width: "100%",
                    padding: "8px",
                    paddingRight: "40px",
                    borderRadius: "4px",
                    border: passwordsMatch ? "2px solid #27ae60" : "1px solid #ccc",
                    background: passwordsMatch ? "#f0fff0" : "#fff",
                    color: "#333",
                  }}
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  style={{
                    position: "absolute",
                    right: "8px",
                    top: "50%",
                    transform: "translateY(-50%)",
                    background: "none",
                    border: "none",
                    cursor: "pointer",
                    color: "#666",
                    fontSize: "12px",
                  }}
                >
                  {showConfirmPassword ? "Hide" : "Show"}
                </button>
              </div>
              {passwordsMatch && (
                <small style={{ display: "block", marginTop: "5px", color: "#27ae60" }}>
                  ✓ Passwords match
                </small>
              )}
            </div>
          </div>

          <div className="nav-buttons">
            <button
              type="submit"
              className="nav-button success"
              disabled={loading || wordCount !== 12 || !newPassword || !passwordsMatch}
              style={{
                opacity: wordCount === 12 && passwordsMatch ? 1 : 0.5,
                cursor: wordCount === 12 && passwordsMatch && !loading ? "pointer" : "not-allowed",
              }}
            >
              {loading ? "Setting New Password..." : "Complete Recovery"}
            </button>
            <button
              type="button"
              onClick={handleBackToVerify}
              className="nav-button secondary"
              disabled={loading}
            >
              Back to Verification
            </button>
          </div>
        </form>

        {/* What Happens Next */}
        <div
          style={{
            marginTop: "20px",
            padding: "15px",
            background: "#e8f4fd",
            borderRadius: "8px",
            border: "1px solid #b8daff",
          }}
        >
          <strong style={{ color: "#004085" }}>What Happens Next?</strong>
          <ul style={{ margin: "10px 0 0", paddingLeft: "20px", color: "#004085", fontSize: "14px" }}>
            <li>Your master key will be decrypted using your recovery key</li>
            <li>New encryption keys will be generated</li>
            <li>All keys will be re-encrypted with your new password</li>
            <li>Your recovery phrase remains the same for future use</li>
            <li>You'll be able to log in immediately with your new password</li>
          </ul>
        </div>

        {/* Security Notes */}
        <div
          style={{
            marginTop: "15px",
            padding: "10px",
            background: "#f0f0f0",
            borderRadius: "5px",
          }}
        >
          <strong>Security Notes:</strong>
          <ul style={{ margin: "10px 0 0", paddingLeft: "20px", color: "#333", fontSize: "14px" }}>
            <li>Choose a strong, unique password</li>
            <li>Your new password will be used to encrypt your keys</li>
            <li>Keep your recovery phrase safe - it hasn't changed</li>
            <li>All your encrypted data remains accessible</li>
          </ul>
        </div>
      </div>
    </Page>
  );
}

export default CompleteRecovery;
