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

function Register() {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    firstName: "",
    lastName: "",
    phone: "",
    country: "CA",
    timezone: "America/Toronto",
    betaAccessCode: "",
    agreeTermsOfService: false,
    agreePromotions: false,
    agreeToTracking: false,
  });
  const [error, setError] = useState("");
  const [fieldErrors, setFieldErrors] = useState({});
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
    // Clear field error when user types
    if (fieldErrors[name]) {
      setFieldErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

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

    try {
      // Generate production E2EE keys using backend crypto library
      const registrationKeys = await GenerateRegistrationKeys(
        formData.password,
      );

      // Use PBKDF2-SHA256 for KDF (compatible with web frontend)
      // Parameters: 100,000 iterations, 16-byte salt, 32-byte key
      const registerInput = {
        beta_access_code: formData.betaAccessCode,
        email: formData.email,
        first_name: formData.firstName,
        last_name: formData.lastName,
        phone: formData.phone,
        country: formData.country,
        timezone: formData.timezone,
        salt: registrationKeys.salt,
        kdf_algorithm: "PBKDF2-SHA256",
        kdf_iterations: 100000,
        kdf_memory: 0, // Not used for PBKDF2
        kdf_parallelism: 0, // Not used for PBKDF2
        kdf_salt_length: 16,
        kdf_key_length: 32,
        encryptedMasterKey: registrationKeys.encryptedMasterKey,
        publicKey: registrationKeys.publicKey,
        encryptedPrivateKey: registrationKeys.encryptedPrivateKey,
        encryptedRecoveryKey: registrationKeys.encryptedRecoveryKey,
        masterKeyEncryptedWithRecoveryKey:
          registrationKeys.masterKeyEncryptedWithRecoveryKey,
        agree_terms_of_service: formData.agreeTermsOfService,
        agree_promotions: formData.agreePromotions,
        agree_to_tracking_across_third_party_apps_and_services:
          formData.agreeToTracking,
      };

      await RegisterAPI(registerInput);
      setMessage("Registration successful! Redirecting to save recovery code...");

      // Store recovery mnemonic in sessionStorage for the RecoveryCode page
      // This is temporary storage - it will be cleared after the user saves it
      sessionStorage.setItem("recoveryMnemonic", registrationKeys.recoveryMnemonic);
      sessionStorage.setItem("registrationEmail", formData.email);

      // Redirect to recovery code page (user MUST save this before continuing)
      setTimeout(() => {
        navigate("/register/recovery");
      }, 1000);
    } catch (err) {
      // Handle RFC 9457 Problem Details error format
      const errorMessage = err.message || err.toString();

      // Try to parse RFC 9457 format
      try {
        // Check if error contains JSON
        const jsonMatch = errorMessage.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          const problemDetails = JSON.parse(jsonMatch[0]);

          // Set general error
          if (problemDetails.title || problemDetails.detail) {
            setError(problemDetails.detail || problemDetails.title);
          }

          // Set field-specific errors
          if (problemDetails.invalid_params) {
            const errors = {};
            problemDetails.invalid_params.forEach((param) => {
              errors[param.name] = param.reason;
            });
            setFieldErrors(errors);
          }
        } else {
          setError("Registration failed: " + errorMessage);
        }
      } catch (parseErr) {
        setError("Registration failed: " + errorMessage);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page title="Register" showBackButton={true}>
      <form onSubmit={handleRegister} style={{ maxWidth: "500px" }}>
        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="betaAccessCode"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Beta Access Code
          </label>
          <input
            type="text"
            id="betaAccessCode"
            name="betaAccessCode"
            value={formData.betaAccessCode}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.beta_access_code && (
            <small style={{ color: "red" }}>
              {fieldErrors.beta_access_code}
            </small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="email"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Email
          </label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.email && (
            <small style={{ color: "red" }}>{fieldErrors.email}</small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="firstName"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            First Name
          </label>
          <input
            type="text"
            id="firstName"
            name="firstName"
            value={formData.firstName}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.first_name && (
            <small style={{ color: "red" }}>{fieldErrors.first_name}</small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="lastName"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Last Name
          </label>
          <input
            type="text"
            id="lastName"
            name="lastName"
            value={formData.lastName}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.last_name && (
            <small style={{ color: "red" }}>{fieldErrors.last_name}</small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="phone"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Phone (Optional)
          </label>
          <input
            type="tel"
            id="phone"
            name="phone"
            value={formData.phone}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.phone && (
            <small style={{ color: "red" }}>{fieldErrors.phone}</small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="country"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Country
          </label>
          <input
            type="text"
            id="country"
            name="country"
            value={formData.country}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.country && (
            <small style={{ color: "red" }}>{fieldErrors.country}</small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="timezone"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Timezone
          </label>
          <input
            type="text"
            id="timezone"
            name="timezone"
            value={formData.timezone}
            onChange={handleInputChange}
            style={{ width: "100%", padding: "8px" }}
          />
          {fieldErrors.timezone && (
            <small style={{ color: "red" }}>{fieldErrors.timezone}</small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            htmlFor="password"
            style={{
              display: "block",
              marginBottom: "5px",
              fontWeight: "bold",
              color: "#333",
            }}
          >
            Password (Used for E2EE)
          </label>
          <input
            type="password"
            id="password"
            name="password"
            value={formData.password}
            onChange={handleInputChange}
            minLength={8}
            style={{ width: "100%", padding: "8px" }}
          />
          <small style={{ display: "block", marginTop: "5px", color: "#666" }}>
            Will be used to encrypt your data (not stored on server). Minimum 8
            characters.
          </small>
          {fieldErrors.password && (
            <small style={{ color: "red", display: "block" }}>
              {fieldErrors.password}
            </small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              cursor: "pointer",
              color: "#333",
            }}
          >
            <input
              type="checkbox"
              name="agreeTermsOfService"
              checked={formData.agreeTermsOfService}
              onChange={handleInputChange}
              style={{ marginRight: "8px" }}
            />
            <span>I agree to the Terms of Service</span>
          </label>
          {fieldErrors.agree_terms_of_service && (
            <small style={{ color: "red" }}>
              {fieldErrors.agree_terms_of_service}
            </small>
          )}
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              cursor: "pointer",
              color: "#333",
            }}
          >
            <input
              type="checkbox"
              name="agreePromotions"
              checked={formData.agreePromotions}
              onChange={handleInputChange}
              style={{ marginRight: "8px" }}
            />
            <span>I agree to receive promotional emails</span>
          </label>
        </div>

        <div style={{ marginBottom: "15px" }}>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              cursor: "pointer",
              color: "#333",
            }}
          >
            <input
              type="checkbox"
              name="agreeToTracking"
              checked={formData.agreeToTracking}
              onChange={handleInputChange}
              style={{ marginRight: "8px" }}
            />
            <span>
              I agree to tracking across third-party apps and services
            </span>
          </label>
        </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 ? "Registering..." : "Register"}
          </button>
          <Link to="/login" className="nav-button secondary">
            Already have an account?
          </Link>
        </div>

        <div
          style={{
            marginTop: "20px",
            padding: "10px",
            background: "#f0f0f0",
            borderRadius: "5px",
          }}
        >
          <strong>Security:</strong> Your password is used to generate
          encryption keys locally and is never sent to the server. All keys are
          encrypted using industry-standard PBKDF2-SHA256 and XSalsa20-Poly1305.
        </div>
      </form>
    </Page>
  );
}

export default Register;
