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

function RequestOTT() {
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

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

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

    // Check if Wails runtime is available
    if (!window.go || !window.go.app || !window.go.app.Application) {
      setError("Application not ready. Please wait a moment and try again.");
      setLoading(false);
      return;
    }

    try {
      await RequestOTTAPI(email);
      setMessage("One-time token sent! Check your email.");

      // Redirect to verify OTT page with email
      setTimeout(() => {
        navigate(`/login/verify-ott?email=${encodeURIComponent(email)}`);
      }, 1000);
    } catch (err) {
      const errorMessage = err.message || err.toString();

      // 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("Failed to send OTT: " + errorMessage);
        }
      } catch (parseErr) {
        setError("Failed to send OTT: " + errorMessage);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page title="Login" showBackButton={true}>
      <form onSubmit={handleSubmit} style={{ maxWidth: "400px" }}>
        <p style={{ marginBottom: "20px", color: "#333" }}>
          Enter your email to receive a one-time token.
        </p>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="email"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Email
          </label>
          <input
            type="email"
            id="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="your@email.com"
            style={{ width: "100%", padding: "8px" }}
            autoFocus
          />
        </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" disabled={loading}>
            {loading ? "Sending..." : "Send One-Time Token"}
          </button>
          <Link to="/register" className="nav-button secondary">
            Need an account?
          </Link>
          <Link to="/recovery" className="nav-button secondary">
            Forgot password?
          </Link>
        </div>
      </form>
    </Page>
  );
}

export default RequestOTT;
