// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Register/Register.jsx
// UIX version - User Registration with E2EE
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useNavigate, Link } from "react-router";
import { useServices } from "../../../services/Services";
import { Card, Input, Select, Checkbox, Button, Alert, GDPRFooter, NavBar, AuthPageHeader } from "../../../components/UIX";
import { useUIXTheme } from "../../../components/UIX/themes/useUIXTheme";
import {
  ArrowRightIcon,
  LockClosedIcon,
  ShieldCheckIcon,
  CheckIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  GlobeAltIcon,
  ClockIcon,
  KeyIcon,
  ServerIcon,
  TicketIcon,
} from "@heroicons/react/24/outline";

const Register = () => {
  const navigate = useNavigate();
  const { authManager } = useServices();
  const { getThemeClasses } = useUIXTheme();

  // Refs for cleanup and preventing state updates after unmount
  const isMountedRef = useRef(true);

  const [formData, setFormData] = useState({
    beta_access_code: "",
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    country: "Canada",
    timezone: "America/Toronto",
    agree_terms_of_service: false,
    agree_promotions: false,
    agree_to_tracking_across_third_party_apps_and_services: false,
    module: 1, // 1 = MapleFile, 2 = PaperCloud
    password: "", // This won't be sent to server, used for E2EE key generation
  });

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [generalError, setGeneralError] = useState("");
  const [keyGenerationProgress, setKeyGenerationProgress] = useState(false);

  // Cleanup effect - prevents memory leaks
  useEffect(() => {
    isMountedRef.current = true;

    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Memoize options arrays to prevent recreations
  const countries = useMemo(
    () => [
      { value: "Canada", label: "Canada" },
      { value: "United States", label: "United States" },
      { value: "United Kingdom", label: "United Kingdom" },
      { value: "Australia", label: "Australia" },
      { value: "Germany", label: "Germany" },
      { value: "France", label: "France" },
      { value: "Japan", label: "Japan" },
      { value: "South Korea", label: "South Korea" },
      { value: "Brazil", label: "Brazil" },
      { value: "Mexico", label: "Mexico" },
      { value: "India", label: "India" },
      { value: "Other", label: "Other" },
    ],
    [],
  );

  const timezones = useMemo(
    () => [
      { value: "America/Toronto", label: "Toronto (EST/EDT)" },
      { value: "America/Vancouver", label: "Vancouver (PST/PDT)" },
      { value: "America/New_York", label: "New York (EST/EDT)" },
      { value: "America/Los_Angeles", label: "Los Angeles (PST/PDT)" },
      { value: "America/Chicago", label: "Chicago (CST/CDT)" },
      { value: "America/Denver", label: "Denver (MST/MDT)" },
      { value: "Europe/London", label: "London (GMT/BST)" },
      { value: "Europe/Paris", label: "Paris (CET/CEST)" },
      { value: "Europe/Berlin", label: "Berlin (CET/CEST)" },
      { value: "Asia/Tokyo", label: "Tokyo (JST)" },
      { value: "Asia/Seoul", label: "Seoul (KST)" },
      { value: "Australia/Sydney", label: "Sydney (AEST/AEDT)" },
      { value: "UTC", label: "UTC" },
    ],
    [],
  );

  // UIX Input onChange receives value directly, not event
  const handleInputChange = useCallback((name, value) => {
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));

    // Clear field-specific error when user starts typing
    setErrors((prev) => {
      if (prev[name]) {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      }
      return prev;
    });

    setGeneralError("");
  }, []);

  // Client-side validation to prevent expensive crypto operations with invalid data
  const validateForm = useCallback(() => {
    const newErrors = {};

    // Required field validation
    if (!formData.beta_access_code.trim()) {
      newErrors.beta_access_code = "Beta access code is required";
    }

    if (!formData.first_name.trim()) {
      newErrors.first_name = "First name is required";
    }

    if (!formData.last_name.trim()) {
      newErrors.last_name = "Last name is required";
    }

    if (!formData.email.trim()) {
      newErrors.email = "Email is required";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = "Please enter a valid email address";
    }

    if (!formData.phone.trim()) {
      newErrors.phone = "Phone number is required";
    }

    if (!formData.password) {
      newErrors.password = "Master password is required";
    } else if (formData.password.length < 8) {
      newErrors.password = "Master password must be at least 8 characters";
    }

    if (!formData.agree_terms_of_service) {
      newErrors.agree_terms_of_service = "You must agree to the Terms of Service";
    }

    return newErrors;
  }, [formData]);

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();

      // Prevent state updates if component is unmounted
      if (!isMountedRef.current) return;

      // Validate form before expensive crypto operations
      const validationErrors = validateForm();
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        setGeneralError("Please fix the errors above before continuing");
        return;
      }

      setLoading(true);
      setErrors({});
      setGeneralError("");
      setKeyGenerationProgress(true);

      try {
        // Log only in development - no sensitive data
        if (import.meta.env.DEV) {
          console.log("[Register] Generating encryption data via AuthManager...");
        }

        // Generate E2EE data using the crypto service via AuthManager
        const e2eeData = await authManager.generateE2EEData(formData.password);

        if (!isMountedRef.current) return;

        if (import.meta.env.DEV) {
          console.log("[Register] Encryption data generated successfully!");
        }

        // Extract the mnemonic and remove it from the data sent to server
        const { recoveryMnemonic, ...e2eeDataForServer } = e2eeData;

        // Prepare registration data - sanitize inputs
        const registrationData = {
          beta_access_code: formData.beta_access_code.trim(),
          first_name: formData.first_name.trim(),
          last_name: formData.last_name.trim(),
          email: formData.email.trim().toLowerCase(),
          phone: formData.phone.trim(),
          country: formData.country,
          timezone: formData.timezone,
          agree_terms_of_service: formData.agree_terms_of_service,
          agree_promotions: formData.agree_promotions,
          agree_to_tracking_across_third_party_apps_and_services:
            formData.agree_to_tracking_across_third_party_apps_and_services,
          module: formData.module,
          ...e2eeDataForServer,
        };

        setKeyGenerationProgress(false);

        if (import.meta.env.DEV) {
          console.log("[Register] Sending registration request via AuthManager...");
        }

        const result = await authManager.registerUser(registrationData);

        if (!isMountedRef.current) return;

        if (import.meta.env.DEV) {
          console.log("[Register] Registration successful via AuthManager");
        }

        // Store data for next page - include the recovery mnemonic
        const registrationWithMnemonic = {
          ...result,
          recoveryMnemonic: recoveryMnemonic,
        };

        sessionStorage.setItem(
          "registrationResult",
          JSON.stringify(registrationWithMnemonic),
        );
        sessionStorage.setItem("registeredEmail", formData.email);

        // Navigate to recovery code page
        navigate("/register/recovery");
      } catch (error) {
        if (!isMountedRef.current) return;

        // Log only in development
        if (import.meta.env.DEV) {
          console.error("[Register] Registration failed:", error);
        }

        // Display RFC 9457 errors from backend
        if (error.fieldErrors && Object.keys(error.fieldErrors).length > 0) {
          setErrors(error.fieldErrors);
        }

        // Set general error message - sanitize technical details
        if (error.message) {
          let userMessage = error.message;

          // Sanitize technical error messages
          if (
            userMessage.includes("method not found") ||
            userMessage.includes("not defined") ||
            userMessage.includes("undefined")
          ) {
            userMessage = "Service temporarily unavailable. Please try again later.";
          }

          setGeneralError(userMessage);
        } else if (error.detail) {
          // RFC 9457 detail field
          setGeneralError(error.detail);
        } else {
          // Fallback for unexpected error formats
          setGeneralError("An error occurred during registration. Please try again.");
        }
      } finally {
        if (isMountedRef.current) {
          setLoading(false);
          setKeyGenerationProgress(false);
        }
      }
    },
    [formData, authManager, navigate, validateForm],
  );

  return (
    <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")} flex flex-col`}>
      {/* Navigation */}
      <NavBar
        links={[{ to: "/login", label: "Already have an account?" }]}
      />

      {/* Main Content */}
      <div className="flex-1 py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-2xl mx-auto">
          {/* Header */}
          <AuthPageHeader
            title="Create Your Secure Account"
            icon={UserIcon}
          />
          <div className="text-center mb-8">
            <p className={`${getThemeClasses("text-secondary")} mb-2`}>
              Join MapleFile and protect your files with end-to-end encryption
            </p>
            <div className={`flex items-center justify-center space-x-2 text-sm ${getThemeClasses("text-secondary")}`}>
              <ShieldCheckIcon className="h-4 w-4" />
              <span>Zero-knowledge architecture with ChaCha20-Poly1305 encryption</span>
            </div>
          </div>

          {/* Form Card */}
          <Card className="shadow-2xl animate-fade-in-up-delay">
            {/* Error Alert */}
            {(generalError || Object.keys(errors).length > 0) && (
              <Alert type="error" dismissible onDismiss={() => { setGeneralError(""); setErrors({}); }}>
                <div>
                  <h3 className="text-base font-bold mb-2">Registration Failed</h3>
                  {generalError && (
                    <p className="text-sm mb-3">{generalError}</p>
                  )}
                  {Object.keys(errors).length > 0 && (
                    <div>
                      <p className="text-sm font-semibold mb-2">
                        Please fix the following errors:
                      </p>
                      <ul className="list-disc list-inside space-y-1.5 text-sm">
                        {Object.entries(errors).map(([field, message]) => (
                          <li key={field} className="ml-1">
                            <span className="font-medium">
                              {field.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase())}
                            </span>
                            : {message}
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}
                </div>
              </Alert>
            )}

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Beta Access Code */}
              <Input
                label="Beta Access Code"
                type="text"
                name="beta_access_code"
                placeholder="Enter your beta access code"
                value={formData.beta_access_code}
                onChange={(value) => handleInputChange("beta_access_code", value)}
                error={errors.beta_access_code}
                required
                icon={TicketIcon}
                disabled={loading}
              />

              {/* Name Fields */}
              <div className="grid grid-cols-2 gap-4">
                <Input
                  label="First Name"
                  type="text"
                  name="first_name"
                  placeholder="John"
                  value={formData.first_name}
                  onChange={(value) => handleInputChange("first_name", value)}
                  error={errors.first_name}
                  required
                  disabled={loading}
                />
                <Input
                  label="Last Name"
                  type="text"
                  name="last_name"
                  placeholder="Doe"
                  value={formData.last_name}
                  onChange={(value) => handleInputChange("last_name", value)}
                  error={errors.last_name}
                  required
                  disabled={loading}
                />
              </div>

              {/* Email */}
              <Input
                label="Email Address"
                type="email"
                name="email"
                placeholder="john.doe@example.com"
                value={formData.email}
                onChange={(value) => handleInputChange("email", value)}
                error={errors.email}
                required
                icon={EnvelopeIcon}
                disabled={loading}
                autoComplete="email"
              />

              {/* Phone */}
              <Input
                label="Phone Number"
                type="tel"
                name="phone"
                placeholder="+1 (555) 123-4567"
                value={formData.phone}
                onChange={(value) => handleInputChange("phone", value)}
                error={errors.phone}
                required
                icon={PhoneIcon}
                disabled={loading}
                autoComplete="tel"
              />

              {/* Location Fields */}
              <div className="grid grid-cols-2 gap-4">
                <Select
                  label="Country"
                  name="country"
                  value={formData.country}
                  onChange={(value) => handleInputChange("country", value)}
                  options={countries}
                  icon={GlobeAltIcon}
                  disabled={loading}
                />
                <Select
                  label="Timezone"
                  name="timezone"
                  value={formData.timezone}
                  onChange={(value) => handleInputChange("timezone", value)}
                  options={timezones}
                  icon={ClockIcon}
                  disabled={loading}
                />
              </div>

              {/* Master Password Section */}
              <div className={`space-y-4 p-4 rounded-lg border ${getThemeClasses("bg-surface")} ${getThemeClasses("border-primary")}`}>
                <h3 className={`text-sm font-semibold ${getThemeClasses("text-primary")} flex items-center`}>
                  <KeyIcon className="h-4 w-4 mr-2" />
                  Master Password for Encryption
                </h3>
                <p className={`text-xs ${getThemeClasses("text-secondary")}`}>
                  <strong>GDPR Notice:</strong> This password generates your encryption keys locally in your browser and is <strong>never stored on our servers or transmitted over the network</strong>. We have zero knowledge of your master password, ensuring complete privacy.
                </p>

                {/* Password Field */}
                <Input
                  label="Master Password"
                  type="password"
                  name="password"
                  value={formData.password}
                  onChange={(value) => handleInputChange("password", value)}
                  placeholder="Enter a strong password"
                  disabled={loading}
                  required
                  error={errors.password}
                  icon={KeyIcon}
                  showPasswordToggle={true}
                />
                {/* Password Warning */}
                <Alert type="warning" className="mt-3">
                  <div className="text-sm">
                    <p className="font-semibold mb-1">Important: Save your master password!</p>
                    <ul className="list-disc list-inside space-y-1 text-xs">
                      <li>This password cannot be recovered if lost</li>
                      <li>We cannot reset it for you due to end-to-end encryption</li>
                      <li>Write it down and store it in a safe place</li>
                    </ul>
                  </div>
                </Alert>
              </div>

              {/* Agreements */}
              <div className="space-y-3">
                {/* Terms of Service */}
                <Checkbox
                  label={
                    <span>
                      I agree to the{" "}
                      <Link to="/terms" className={`${getThemeClasses("link-primary")} underline`}>
                        Terms of Service
                      </Link>{" "}
                      and{" "}
                      <Link to="/privacy" className={`${getThemeClasses("link-primary")} underline`}>
                        Privacy Policy
                      </Link>{" "}
                      *
                    </span>
                  }
                  checked={formData.agree_terms_of_service}
                  onChange={(checked) =>
                    handleInputChange("agree_terms_of_service", checked)
                  }
                  disabled={loading}
                />
                {errors.agree_terms_of_service && (
                  <p className={`ml-7 text-xs ${getThemeClasses("text-danger")}`}>
                    {errors.agree_terms_of_service}
                  </p>
                )}

                {/* Promotional Communications */}
                <div>
                  <Checkbox
                    label="I consent to receiving product updates, feature announcements, and security alerts via email"
                    checked={formData.agree_promotions}
                    onChange={(checked) => handleInputChange("agree_promotions", checked)}
                    disabled={loading}
                  />
                  <p className={`ml-7 mt-1 text-xs ${getThemeClasses("text-secondary")}`}>
                    We'll use your email address to send you important updates. You can unsubscribe anytime. Data retention: Until you unsubscribe or close your account.
                  </p>
                </div>

                {/* Tracking */}
                <div>
                  <Checkbox
                    label="I consent to anonymous usage analytics to help improve MapleFile (optional)"
                    checked={formData.agree_to_tracking_across_third_party_apps_and_services}
                    onChange={(checked) =>
                      handleInputChange(
                        "agree_to_tracking_across_third_party_apps_and_services",
                        checked,
                      )
                    }
                    disabled={loading}
                  />
                  <p className={`ml-7 mt-1 text-xs ${getThemeClasses("text-secondary")}`}>
                    We collect anonymized usage data (page views, feature usage) to improve our service. No personal files or content are tracked. Data retention: 24 months. You can opt-out anytime in settings.
                  </p>
                </div>
              </div>

              {/* Submit Button */}
              <Button
                type="submit"
                variant="primary"
                fullWidth
                disabled={loading}
                loading={loading}
                loadingText={
                  keyGenerationProgress
                    ? "Generating encryption keys..."
                    : "Creating your secure account..."
                }
              >
                <span className="inline-flex items-center justify-center gap-2">
                  <ShieldCheckIcon className="h-5 w-5" />
                  <span>Create Secure Account</span>
                  <ArrowRightIcon className="h-4 w-4" />
                </span>
              </Button>
            </form>

            {/* Security Trust Section */}
            <Card className={`mt-8 ${getThemeClasses("bg-surface")}`}>
              <div className="flex items-center justify-center">
                <div className="flex items-center space-x-4">
                  <div className="flex items-center space-x-1">
                    <LockClosedIcon className="h-4 w-4" />
                    <span className={`text-xs font-semibold ${getThemeClasses("text-primary")}`}>
                      ChaCha20-Poly1305
                    </span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <ServerIcon className="h-4 w-4" />
                    <span className={`text-xs font-semibold ${getThemeClasses("text-primary")}`}>
                      Canadian Hosted
                    </span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <KeyIcon className="h-4 w-4" />
                    <span className={`text-xs font-semibold ${getThemeClasses("text-primary")}`}>
                      Zero Knowledge
                    </span>
                  </div>
                </div>
              </div>
            </Card>

            {/* Info Section */}
            <Alert type="info" className="mt-6">
              <div>
                <h3 className="text-sm font-semibold mb-3">
                  What happens next?
                </h3>
                <ul className="text-sm space-y-2">
                  <li className="flex items-start">
                    <CheckIcon className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
                    We'll generate your encryption keys locally in your browser
                  </li>
                  <li className="flex items-start">
                    <CheckIcon className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
                    You'll receive a recovery phrase to backup your account
                  </li>
                  <li className="flex items-start">
                    <CheckIcon className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
                    We'll send a verification email to confirm your address
                  </li>
                  <li className="flex items-start">
                    <CheckIcon className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
                    Your files will be encrypted before leaving your device
                  </li>
                </ul>
                <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
                  <p className="text-xs font-semibold mb-2">Data We Collect & Why (GDPR Transparency):</p>
                  <ul className="text-xs space-y-1">
                    <li><strong>• Name & Email:</strong> Account management, authentication, communication (Legal basis: Contract)</li>
                    <li><strong>• Phone:</strong> Account recovery, security verification (Legal basis: Contract)</li>
                    <li><strong>• Country & Timezone:</strong> Localization, service delivery (Legal basis: Contract)</li>
                    <li><strong>• Encrypted File Metadata:</strong> File management (Legal basis: Contract)</li>
                    <li><strong>• Master Password:</strong> Never collected - stays in your browser only</li>
                  </ul>
                </div>
              </div>
            </Alert>

            {/* Alternative Actions */}
            <div className="mt-6 text-center text-sm">
              <span className={getThemeClasses("text-secondary")}>Already have an account? </span>
              <Link
                to="/login"
                className={`${getThemeClasses("link-primary")} font-medium hover:underline transition-colors duration-200`}
              >
                Sign in
              </Link>
            </div>
          </Card>
        </div>
      </div>

      {/* Footer */}
      <GDPRFooter />
    </div>
  );
};

export default Register;
