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

function CompleteLogin() {
  const navigate = useNavigate();
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");
  const [challengeData, setChallengeData] = useState(null);

  useEffect(() => {
    // Get challenge data from sessionStorage
    const storedData = sessionStorage.getItem("loginChallenge");
    if (!storedData) {
      setError("Missing login challenge data. Please start login again.");
      return;
    }

    try {
      const data = JSON.parse(storedData);
      setChallengeData(data);
    } catch (err) {
      setError("Invalid challenge data. Please start login again.");
    }
  }, []);

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

    if (!challengeData) {
      setError("Missing challenge data. Please return to login.");
      setLoading(false);
      return;
    }

    if (!password) {
      setError("Please enter your password.");
      setLoading(false);
      return;
    }

    try {
      // Step 1: Decrypt the login challenge using E2EE
      setMessage("Decrypting challenge with E2EE...");

      const decryptedChallenge = await DecryptLoginChallenge(
        password,
        challengeData.salt,
        challengeData.encryptedMasterKey,
        challengeData.encryptedChallenge,
        challengeData.encryptedPrivateKey,
        challengeData.publicKey,
        // Pass KDF algorithm
        challengeData.kdfAlgorithm || "PBKDF2-SHA256",
      );

      // Step 2: Complete login with the decrypted challenge
      setMessage("Completing login...");

      const loginInput = {
        email: challengeData.email,
        challengeId: challengeData.challengeId,
        decryptedData: decryptedChallenge,
        password: password, // Pass password to backend for storage
        // Pass encrypted data for future password verification
        salt: challengeData.salt,
        encryptedMasterKey: challengeData.encryptedMasterKey,
        encryptedPrivateKey: challengeData.encryptedPrivateKey,
        publicKey: challengeData.publicKey,
        // Pass KDF algorithm for master key caching
        kdfAlgorithm: challengeData.kdfAlgorithm || "PBKDF2-SHA256",
      };

      await CompleteLoginAPI(loginInput);

      // Clear challenge data from sessionStorage
      sessionStorage.removeItem("loginChallenge");

      setMessage("Login successful! Redirecting to dashboard...");

      // Redirect to dashboard
      setTimeout(() => {
        navigate("/dashboard");
      }, 1000);
    } catch (err) {
      const errorMessage = err.message || err.toString();

      // Check for wrong password error
      if (
        errorMessage.includes("wrong password") ||
        errorMessage.includes("failed to decrypt master key")
      ) {
        setError("Incorrect password. Please try again.");
      } else {
        // Try to parse RFC 9457 format
        try {
          const jsonMatch = errorMessage.match(/\{[\s\S]*\}/);
          if (jsonMatch) {
            const problemDetails = JSON.parse(jsonMatch[0]);
            setError(
              problemDetails.detail || problemDetails.title || errorMessage,
            );
          } else {
            setError("Login failed: " + errorMessage);
          }
        } catch (parseErr) {
          setError("Login failed: " + errorMessage);
        }
      }
    } finally {
      setLoading(false);
    }
  };

  if (!challengeData && !error) {
    return (
      <Page title="Complete Login" showBackButton={true}>
        <p style={{ color: "#666" }}>Loading...</p>
      </Page>
    );
  }

  return (
    <Page title="Complete Login" showBackButton={true}>
      <form onSubmit={handleSubmit} style={{ maxWidth: "400px" }}>
        <p style={{ marginBottom: "20px", color: "#333" }}>
          Enter your password to decrypt your keys and complete the login
          process.
        </p>

        {challengeData && (
          <div style={{ marginBottom: "15px" }}>
            <label
              style={{
                display: "block",
                marginBottom: "5px",
                fontWeight: "bold",
                color: "#333",
              }}
            >
              Email
            </label>
            <input
              type="email"
              value={challengeData.email}
              style={{
                width: "100%",
                padding: "8px",
                backgroundColor: "#f5f5f5",
              }}
              readOnly
            />
          </div>
        )}

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="password"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Password
          </label>
          <input
            type="password"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Enter your password"
            style={{ width: "100%", padding: "8px" }}
            autoFocus
            minLength={8}
          />
          <small style={{ display: "block", marginTop: "5px", color: "#666" }}>
            Your password is used to decrypt your encryption keys locally.
          </small>
        </div>

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

        <div className="nav-buttons">
          <button
            type="submit"
            className="nav-button success"
            disabled={loading || !challengeData}
          >
            {loading ? "Logging in..." : "Complete Login"}
          </button>
          <Link to="/login" className="nav-button secondary">
            Start Over
          </Link>
          <Link to="/recovery" className="nav-button secondary">
            Forgot Password?
          </Link>
        </div>

        <div
          style={{
            marginTop: "20px",
            padding: "10px",
            background: "#f0f0f0",
            borderRadius: "5px",
          }}
        >
          <strong>Security:</strong> Your password never leaves this device.
          It's used only to decrypt your keys locally using industry-standard
          cryptographic algorithms.
        </div>
      </form>
    </Page>
  );
}

export default CompleteLogin;
