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

function VerifyEmail() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  useEffect(() => {
    // Get email from URL query parameter
    const emailParam = searchParams.get("email");
    if (emailParam) {
      setEmail(emailParam);
    }
  }, [searchParams]);

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

    if (!email) {
      setError("Email is missing. Please return to registration.");
      setLoading(false);
      return;
    }

    if (!verificationCode) {
      setError("Please enter the verification code.");
      setLoading(false);
      return;
    }

    try {
      await VerifyEmailAPI(email, verificationCode);
      setMessage("Email verified successfully! Redirecting...");

      // Redirect to success page after 1 second
      setTimeout(() => {
        navigate("/register/verify-success");
      }, 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("Verification failed: " + errorMessage);
        }
      } catch (parseErr) {
        setError("Verification failed: " + errorMessage);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page title="Verify Email" showBackButton={true}>
      <div style={{ maxWidth: "400px" }}>
        <p style={{ marginBottom: "20px", color: "#333" }}>
          Please check your email <strong>{email}</strong> and enter the
          verification code sent to you.
        </p>

        <form onSubmit={handleVerify}>
          <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)}
              style={{
                width: "100%",
                padding: "8px",
                backgroundColor: "#f5f5f5",
              }}
              readOnly
            />
          </div>

          <div style={{ marginBottom: "15px" }}>
            <label
              htmlFor="code"
              style={{
                display: "block",
                marginBottom: "5px",
                fontWeight: "bold",
                color: "#333",
              }}
            >
              Verification Code
            </label>
            <input
              type="text"
              id="code"
              value={verificationCode}
              onChange={(e) => setVerificationCode(e.target.value)}
              placeholder="Enter 8-digit code"
              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 ? "Verifying..." : "Verify Email"}
            </button>
            <Link to="/login" className="nav-button secondary">
              Back to Login
            </Link>
          </div>
        </form>

        <div
          style={{
            marginTop: "20px",
            padding: "10px",
            background: "#f0f0f0",
            borderRadius: "5px",
          }}
        >
          <p style={{ margin: 0, fontSize: "14px", color: "#666" }}>
            <strong>Didn't receive the code?</strong> Check your spam folder or
            contact support.
          </p>
        </div>
      </div>
    </Page>
  );
}

export default VerifyEmail;
