// File: monorepo/maplefile-frontend/src/pages/User/Me/Detail.jsx
import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useNavigate } from "react-router";
import { useAuth } from "../../../services/Services";
import withPasswordProtection from "../../../hocs/withPasswordProtection";
import Layout from "../../../components/Layout/Layout";
import {
  Button,
  Card,
  Breadcrumb,
  Input,
  Select,
  Alert,
  Badge,
  Checkbox,
  Spinner,
  useUIXTheme,
} from "../../../components/UIX";
import {
  UserIcon,
  ShieldCheckIcon,
  CheckIcon,
  ExclamationTriangleIcon,
  ArrowPathIcon,
  DocumentTextIcon,
  CalendarIcon,
  EnvelopeIcon,
  PhoneIcon,
  GlobeAltIcon,
  ClockIcon,
  PencilIcon,
  TrashIcon,
  NoSymbolIcon,
  ChevronRightIcon,
  ArrowDownTrayIcon,
  TagIcon,
  HomeIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

const MeDetail = () => {
  const navigate = useNavigate();
  const { authManager, meManager } = useAuth();
  const { getThemeClasses } = useUIXTheme();
  const isMountedRef = useRef(true);

  // Page state
  const [userProfile, setUserProfile] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isInitialized, setIsInitialized] = useState(false);
  const [error, setError] = useState("");
  const [activeTab, setActiveTab] = useState("profile");

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Edit mode states
  const [isEditing, setIsEditing] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [editError, setEditError] = useState("");
  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    phone: "",
    country: "",
    timezone: "",
    share_notifications_enabled: true,
  });

  // Email change states
  const [showEmailChangeModal, setShowEmailChangeModal] = useState(false);
  const [emailChangeStep, setEmailChangeStep] = useState(1); // 1 = request, 2 = verify
  const [newEmail, setNewEmail] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [emailChangeLoading, setEmailChangeLoading] = useState(false);
  const [emailChangeError, setEmailChangeError] = useState("");
  const [emailChangeSuccess, setEmailChangeSuccess] = useState("");

  // Note: Delete account functionality moved to dedicated /me/delete-account page

  // Countries and timezones lists
  const countries = [
    "Canada",
    "United States",
    "United Kingdom",
    "Australia",
    "Germany",
    "France",
    "Japan",
    "South Korea",
    "Brazil",
    "Mexico",
    "India",
    "Other",
  ];

  const timezones = [
    { 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" },
  ];

  const tabs = [
    { id: "profile", label: "Profile", icon: UserIcon },
    { id: "security", label: "Security", icon: ShieldCheckIcon },
    { id: "tags", label: "Tags", icon: TagIcon },
  ];

  const loadUserProfile = useCallback(
    async (forceRefresh = false) => {
      if (!meManager) return;

      setIsLoading(true);
      setError("");

      try {
        if (import.meta.env.DEV) {
          console.log(
            "[Profile] Loading user profile...",
            forceRefresh ? "(force refresh)" : "",
          );
        }
        const profile = forceRefresh
          ? await meManager.refreshUserData()
          : await meManager.getCurrentUser();

        if (isMountedRef.current) {
          setUserProfile(profile);
          setFormData({
            first_name: profile.first_name || "",
            last_name: profile.last_name || "",
            phone: profile.phone || "",
            country: profile.country || "Canada",
            timezone: profile.timezone || "America/Toronto",
            share_notifications_enabled:
              profile.share_notifications_enabled !== false,
          });
          setIsInitialized(true);
          if (import.meta.env.DEV) {
            console.log("[Profile] Profile loaded successfully");
          }
        }
      } catch (err) {
        if (isMountedRef.current) {
          if (import.meta.env.DEV) {
            console.error("[Profile] Failed to load profile:", err);
          }
          setError(err.message || "Failed to load profile.");
          setIsInitialized(true);
        }
      } finally {
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    },
    [meManager],
  );

  useEffect(() => {
    if (meManager && authManager?.isAuthenticated() && !isInitialized) {
      loadUserProfile();
    }
  }, [meManager, authManager, isInitialized, loadUserProfile]);

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
    if (editError) setEditError("");
  };

  const handleSaveChanges = async (e) => {
    e.preventDefault();
    setEditLoading(true);
    setEditError("");

    try {
      const updatedProfile = await meManager.updateCurrentUser(formData);
      if (isMountedRef.current) {
        setUserProfile(updatedProfile);
        setIsEditing(false);
        if (import.meta.env.DEV) {
          console.log("Profile updated successfully");
        }
      }
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("Failed to update profile:", err);
      }

      // Parse error message - handle both string errors and validation error objects
      let errorMessage = "Failed to update profile";
      if (err.message) {
        try {
          // Try to parse as JSON in case it's a validation error object
          const parsed = JSON.parse(err.message);
          if (typeof parsed === "object") {
            // Convert object to readable error messages
            errorMessage = Object.entries(parsed)
              .map(([field, message]) => `${field}: ${message}`)
              .join(", ");
          } else {
            errorMessage = err.message;
          }
        } catch {
          // Not JSON, use as-is
          errorMessage = err.message;
        }
      }
      if (isMountedRef.current) {
        setEditError(errorMessage);
      }
    } finally {
      if (isMountedRef.current) {
        setEditLoading(false);
      }
    }
  };

  const handleCancelEdit = () => {
    if (userProfile) {
      setFormData({
        first_name: userProfile.first_name || "",
        last_name: userProfile.last_name || "",
        phone: userProfile.phone || "",
        country: userProfile.country || "Canada",
        timezone: userProfile.timezone || "America/Toronto",
        share_notifications_enabled:
          userProfile.share_notifications_enabled !== false,
      });
    }
    setIsEditing(false);
    setEditError("");
  };

  // Delete account handler removed - now using dedicated /me/delete-account page

  // Email change handlers
  const handleEmailChangeRequest = async (e) => {
    e.preventDefault();
    setEmailChangeLoading(true);
    setEmailChangeError("");

    try {
      await meManager.apiService.requestEmailChange(newEmail);
      setEmailChangeStep(2);
      setEmailChangeSuccess(`Verification code sent to ${newEmail}. Please check your email.`);
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("Failed to request email change:", err);
      }
      setEmailChangeError(err.message || "Failed to request email change");
    } finally {
      setEmailChangeLoading(false);
    }
  };

  const handleEmailChangeVerify = async (e) => {
    e.preventDefault();
    setEmailChangeLoading(true);
    setEmailChangeError("");

    try {
      const result = await meManager.apiService.verifyEmailChange(verificationCode);
      setEmailChangeSuccess("Email changed successfully! Refreshing your profile...");

      // Refresh profile to get updated email
      setTimeout(async () => {
        await loadUserProfile(true);
        setShowEmailChangeModal(false);
        setEmailChangeStep(1);
        setNewEmail("");
        setVerificationCode("");
        setEmailChangeSuccess("");
      }, 2000);
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("Failed to verify email change:", err);
      }
      setEmailChangeError(err.message || "Failed to verify email change");
    } finally {
      setEmailChangeLoading(false);
    }
  };

  const handleCancelEmailChange = () => {
    setShowEmailChangeModal(false);
    setEmailChangeStep(1);
    setNewEmail("");
    setVerificationCode("");
    setEmailChangeError("");
    setEmailChangeSuccess("");
    setEmailChangeLoading(false);
  };

  const formatDate = (dateString) => {
    if (!dateString) return "N/A";
    try {
      const date = new Date(dateString);
      // Check if date is valid
      if (isNaN(date.getTime())) {
        return "Invalid Date";
      }
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
        timeZone: "UTC", // Use UTC to avoid timezone shifting
      });
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("Error formatting date:", err, dateString);
      }
      return "Invalid Date";
    }
  };

  const getRoleInfoText = (role) => {
    switch (role) {
      case 1:
        return "Root User";
      case 2:
        return "Company User";
      case 3:
        return "Individual User";
      default:
        return "Unknown";
    }
  };

  // Memoize breadcrumb items
  const breadcrumbItems = useMemo(() => [
    {
      label: "Dashboard",
      to: "/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Settings",
      isActive: true,
      icon: Cog6ToothIcon,
    },
  ], []);

  // Memoize country options for Select
  const countryOptions = useMemo(() =>
    countries.map((c) => ({ value: c, label: c })),
    []
  );

  // Memoize timezone options for Select
  const timezoneOptions = useMemo(() =>
    timezones.map((tz) => ({ value: tz.value, label: tz.label })),
    []
  );

  return (
    <Layout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb Navigation */}
        <Breadcrumb items={breadcrumbItems} />

        {/* Main Card */}
        <Card>
          {/* Header with icon, title, and action button */}
          <div className={`p-6 border-b ${getThemeClasses("border-secondary")}`}>
            <div className="flex flex-col space-y-4 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
              <div className="flex-1 min-w-0">
                <div className="flex items-start">
                  {/* Icon */}
                  <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-gradient-secondary")}`}>
                    <Cog6ToothIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  {/* Title and subtitle */}
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      My Account
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Manage your profile and security settings
                    </p>
                  </div>
                </div>
              </div>
              {/* Action button */}
              <div className="flex-shrink-0">
                <Button
                  onClick={() => loadUserProfile(true)}
                  disabled={isLoading}
                  variant="secondary"
                  icon={ArrowPathIcon}
                  className={isLoading ? "[&>svg]:animate-spin" : ""}
                >
                  {isLoading ? "Refreshing..." : "Refresh"}
                </Button>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="p-6">
            {/* Loading State */}
            {isLoading && !userProfile && (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <Spinner size="lg" className="mx-auto mb-4" />
                  <p className={getThemeClasses("text-secondary")}>Loading your profile...</p>
                </div>
              </div>
            )}

            {/* Error State */}
            {error && !userProfile && (
              <Alert type="error" className="mb-4">
                <div className="flex-1">
                  <h3 className="text-lg font-semibold mb-2">
                    Failed to Load Profile
                  </h3>
                  <p className="mb-3">{error}</p>
                  <Button
                    onClick={() => loadUserProfile(true)}
                    variant="secondary"
                    icon={ArrowPathIcon}
                    size="sm"
                  >
                    Try Again
                  </Button>
                </div>
              </Alert>
            )}

            {userProfile && (
              <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
                {/* Sidebar */}
                <div className="lg:col-span-1">
                  <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6 mb-6 text-center`}>
                    <div className={`h-24 w-24 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl flex items-center justify-center text-white text-3xl font-bold mx-auto mb-4`}>
                      {userProfile.first_name?.charAt(0)}
                      {userProfile.last_name?.charAt(0)}
                    </div>
                    <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                      {userProfile.first_name} {userProfile.last_name}
                    </h2>
                    <p className={`text-sm ${getThemeClasses("text-secondary")}`}>{userProfile.email}</p>
                    <div className="mt-4">
                      <Badge variant="success">
                        <CheckIcon className="h-3 w-3 mr-1" />
                        Verified User
                      </Badge>
                    </div>
                  </div>

                  <nav className="space-y-1" role="navigation" aria-label="Account settings tabs">
                    {tabs.map((tab) => (
                      <button
                        key={tab.id}
                        onClick={() => {
                          if (tab.id === "tags") {
                            navigate("/me/tags");
                          } else {
                            setActiveTab(tab.id);
                          }
                        }}
                        aria-current={activeTab === tab.id ? "page" : undefined}
                        className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-lg transition-all duration-200 ${
                          activeTab === tab.id
                            ? `${getThemeClasses("bg-gradient-secondary")} text-white shadow-md`
                            : `${getThemeClasses("text-secondary")} hover:bg-gray-100`
                        }`}
                      >
                        <tab.icon className="h-5 w-5 mr-3" aria-hidden="true" />
                        {tab.label}
                      </button>
                    ))}
                  </nav>
                </div>

                {/* Main Content */}
                <div className="lg:col-span-3">
                  {/* Profile Tab */}
                  {activeTab === "profile" && (
                    <div className="space-y-6">
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <div className="flex items-center justify-between mb-6">
                          <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                            Personal Information
                          </h3>
                          {!isEditing && (
                            <Button
                              onClick={() => setIsEditing(true)}
                              variant="secondary"
                              icon={PencilIcon}
                            >
                              Edit Profile
                            </Button>
                          )}
                        </div>

                        {isEditing ? (
                          <form onSubmit={handleSaveChanges} className="space-y-4">
                            {editError && (
                              <Alert type="error" onClose={() => setEditError("")}>
                                {editError}
                              </Alert>
                            )}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              <Input
                                id="first_name"
                                name="first_name"
                                label="First Name"
                                type="text"
                                value={formData.first_name}
                                onChange={(value) => {
                                  setFormData((prev) => ({ ...prev, first_name: value }));
                                  if (editError) setEditError("");
                                }}
                                disabled={editLoading}
                                required
                              />
                              <Input
                                id="last_name"
                                name="last_name"
                                label="Last Name"
                                type="text"
                                value={formData.last_name}
                                onChange={(value) => {
                                  setFormData((prev) => ({ ...prev, last_name: value }));
                                  if (editError) setEditError("");
                                }}
                                disabled={editLoading}
                                required
                              />
                              <Input
                                id="phone"
                                name="phone"
                                label="Phone"
                                type="tel"
                                value={formData.phone}
                                onChange={(value) => {
                                  setFormData((prev) => ({ ...prev, phone: value }));
                                  if (editError) setEditError("");
                                }}
                                disabled={editLoading}
                                required
                              />
                              <Select
                                id="country"
                                name="country"
                                label="Country"
                                value={formData.country}
                                onChange={(value) => {
                                  setFormData((prev) => ({ ...prev, country: value }));
                                  if (editError) setEditError("");
                                }}
                                options={countryOptions}
                                disabled={editLoading}
                                required
                              />
                              <Select
                                id="timezone"
                                name="timezone"
                                label="Timezone"
                                value={formData.timezone}
                                onChange={(value) => {
                                  setFormData((prev) => ({ ...prev, timezone: value }));
                                  if (editError) setEditError("");
                                }}
                                options={timezoneOptions}
                                disabled={editLoading}
                                required
                              />
                            </div>

                            <div className="flex justify-end space-x-3 pt-4">
                              <Button
                                type="button"
                                onClick={handleCancelEdit}
                                variant="secondary"
                                disabled={editLoading}
                              >
                                Cancel
                              </Button>
                              <Button
                                type="submit"
                                variant="primary"
                                disabled={editLoading}
                              >
                                {editLoading ? "Saving..." : "Save Changes"}
                              </Button>
                            </div>
                          </form>
                        ) : (
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-6" role="list" aria-label="Profile information">
                            <div className="flex items-start space-x-3" role="listitem">
                              <UserIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Full Name</p>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  {userProfile.first_name} {userProfile.last_name}
                                </p>
                              </div>
                            </div>
                            <div className="flex items-start space-x-3" role="listitem">
                              <EnvelopeIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Email</p>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  {userProfile.email}
                                </p>
                              </div>
                            </div>
                            <div className="flex items-start space-x-3" role="listitem">
                              <PhoneIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Phone</p>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  {userProfile.phone || "N/A"}
                                </p>
                              </div>
                            </div>
                            <div className="flex items-start space-x-3" role="listitem">
                              <GlobeAltIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Country</p>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  {userProfile.country}
                                </p>
                              </div>
                            </div>
                            <div className="flex items-start space-x-3" role="listitem">
                              <ClockIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Timezone</p>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  {userProfile.timezone}
                                </p>
                              </div>
                            </div>
                            <div className="flex items-start space-x-3" role="listitem">
                              <CalendarIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                                  Member Since
                                </p>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  {formatDate(userProfile.created_at)}
                                </p>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>

                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4`}>
                          Account Information
                        </h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6" role="list" aria-label="Account information">
                          <div className="flex items-start space-x-3" role="listitem">
                            <DocumentTextIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                            <div>
                              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>User ID</p>
                              <p className={`font-mono text-sm ${getThemeClasses("text-primary")}`}>
                                {userProfile.id}
                              </p>
                            </div>
                          </div>
                          <div className="flex items-start space-x-3" role="listitem">
                            <ShieldCheckIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mt-0.5`} aria-hidden="true" />
                            <div>
                              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Account Type</p>
                              <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                {getRoleInfoText(
                                  userProfile.user_role || userProfile.role,
                                )}
                              </p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Security Tab */}
                  {activeTab === "security" && (
                    <div className="space-y-6">
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-6`}>
                          Security Settings
                        </h3>
                        <div className="space-y-4">
                          <div className={`p-4 ${getThemeClasses("export-section-success-bg")} border ${getThemeClasses("export-section-success-border")} rounded-lg`}>
                            <div className="flex items-start">
                              <CheckIcon className={`h-5 w-5 ${getThemeClasses("export-section-success-icon")} mr-3 flex-shrink-0 mt-0.5`} aria-hidden="true" />
                              <div>
                                <h4 className={`text-sm font-medium ${getThemeClasses("export-section-success-title")}`}>
                                  Two-Factor Authentication
                                </h4>
                                <p className={`text-sm ${getThemeClasses("export-section-success-text")} mt-1`}>
                                  Your account is protected with 2FA (managed at the
                                  identity provider level).
                                </p>
                              </div>
                            </div>
                          </div>
                          <div className={`p-4 ${getThemeClasses("export-section-info-bg")} border ${getThemeClasses("export-section-info-border")} rounded-lg`}>
                            <div className="flex items-start">
                              <ShieldCheckIcon className={`h-5 w-5 ${getThemeClasses("export-section-info-icon")} mr-3 flex-shrink-0 mt-0.5`} aria-hidden="true" />
                              <div>
                                <h4 className={`text-sm font-medium ${getThemeClasses("export-section-info-title")}`}>
                                  End-to-End Encryption
                                </h4>
                                <p className={`text-sm ${getThemeClasses("export-section-info-text")} mt-1`}>
                                  All your files are encrypted with your keys before
                                  they leave your device.
                                </p>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* Change Email Section */}
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                          Email Address
                        </h3>
                        <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
                          Update your email address. You'll need to verify your new email.
                        </p>

                        {!showEmailChangeModal ? (
                          <div className={`flex items-center justify-between p-4 ${getThemeClasses("bg-muted")} rounded-lg border ${getThemeClasses("border-secondary")}`}>
                            <div className="flex items-start">
                              <EnvelopeIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mr-3 mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  Current Email
                                </p>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                                  {userProfile?.email}
                                </p>
                              </div>
                            </div>
                            <Button
                              onClick={() => setShowEmailChangeModal(true)}
                              variant="secondary"
                              size="sm"
                              icon={PencilIcon}
                            >
                              Change Email
                            </Button>
                          </div>
                        ) : (
                          <div className={`p-4 ${getThemeClasses("bg-muted")} rounded-lg border ${getThemeClasses("border-secondary")}`}>
                            {emailChangeStep === 1 ? (
                              <form onSubmit={handleEmailChangeRequest} className="space-y-4">
                                <div>
                                  <h4 className={`text-md font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                                    Step 1: Enter New Email
                                  </h4>
                                  <p className={`text-sm ${getThemeClasses("text-secondary")} mb-3`}>
                                    We'll send a verification code to your new email address.
                                  </p>
                                </div>

                                {emailChangeError && (
                                  <Alert type="error" onClose={() => setEmailChangeError("")}>
                                    {emailChangeError}
                                  </Alert>
                                )}

                                <Input
                                  id="new_email"
                                  name="new_email"
                                  label="New Email Address"
                                  type="email"
                                  value={newEmail}
                                  onChange={(value) => {
                                    setNewEmail(value);
                                    if (emailChangeError) setEmailChangeError("");
                                  }}
                                  disabled={emailChangeLoading}
                                  required
                                  placeholder="your.new@email.com"
                                />

                                <div className="flex justify-end space-x-3">
                                  <Button
                                    type="button"
                                    onClick={handleCancelEmailChange}
                                    variant="secondary"
                                    disabled={emailChangeLoading}
                                  >
                                    Cancel
                                  </Button>
                                  <Button
                                    type="submit"
                                    variant="primary"
                                    disabled={emailChangeLoading}
                                  >
                                    {emailChangeLoading ? "Sending..." : "Send Code"}
                                  </Button>
                                </div>
                              </form>
                            ) : (
                              <form onSubmit={handleEmailChangeVerify} className="space-y-4">
                                <div>
                                  <h4 className={`text-md font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                                    Step 2: Verify New Email
                                  </h4>
                                  <p className={`text-sm ${getThemeClasses("text-secondary")} mb-3`}>
                                    Enter the 8-digit code sent to <strong>{newEmail}</strong>
                                  </p>
                                </div>

                                {emailChangeSuccess && (
                                  <Alert type="success" onClose={() => setEmailChangeSuccess("")}>
                                    {emailChangeSuccess}
                                  </Alert>
                                )}

                                {emailChangeError && (
                                  <Alert type="error" onClose={() => setEmailChangeError("")}>
                                    {emailChangeError}
                                  </Alert>
                                )}

                                <Input
                                  id="verification_code"
                                  name="verification_code"
                                  label="Verification Code"
                                  type="text"
                                  value={verificationCode}
                                  onChange={(value) => {
                                    setVerificationCode(value);
                                    if (emailChangeError) setEmailChangeError("");
                                  }}
                                  disabled={emailChangeLoading}
                                  required
                                  placeholder="12345678"
                                  maxLength="8"
                                />

                                <div className="flex justify-end space-x-3">
                                  <Button
                                    type="button"
                                    onClick={handleCancelEmailChange}
                                    variant="secondary"
                                    disabled={emailChangeLoading}
                                  >
                                    Cancel
                                  </Button>
                                  <Button
                                    type="submit"
                                    variant="primary"
                                    disabled={emailChangeLoading}
                                  >
                                    {emailChangeLoading ? "Verifying..." : "Verify Email"}
                                  </Button>
                                </div>
                              </form>
                            )}
                          </div>
                        )}
                      </div>

                      {/* Notification Preferences Section */}
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                          Notification Preferences
                        </h3>
                        <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
                          Control how you receive notifications from MapleFile.
                        </p>
                        <div className="space-y-4">
                          <div className={`flex items-start justify-between p-4 ${getThemeClasses("bg-muted")} rounded-lg border ${getThemeClasses("border-secondary")}`}>
                            <div className="flex items-start">
                              <EnvelopeIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mr-3 mt-0.5`} aria-hidden="true" />
                              <div>
                                <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                  Share Notifications
                                </p>
                                <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                                  Receive email notifications when someone shares a
                                  collection with you
                                </p>
                              </div>
                            </div>
                            <Checkbox
                              id="share_notifications_enabled"
                              checked={formData.share_notifications_enabled}
                              onChange={async (checked) => {
                                setFormData((prev) => ({
                                  ...prev,
                                  share_notifications_enabled: checked,
                                }));
                                try {
                                  const updatedProfile =
                                    await meManager.updateCurrentUser({
                                      ...formData,
                                      share_notifications_enabled: checked,
                                    });
                                  if (isMountedRef.current) {
                                    setUserProfile(updatedProfile);
                                  }
                                } catch (err) {
                                  if (import.meta.env.DEV) {
                                    console.error(
                                      "Failed to update notification preference:",
                                      err,
                                    );
                                  }
                                  // Revert on error
                                  if (isMountedRef.current) {
                                    setFormData((prev) => ({
                                      ...prev,
                                      share_notifications_enabled: !checked,
                                    }));
                                  }
                                }
                              }}
                              aria-label="Enable share notifications"
                            />
                          </div>
                        </div>
                      </div>

                      {/* Blocked Users Section */}
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                          Privacy Settings
                        </h3>
                        <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
                          Manage users who can interact with you.
                        </p>
                        <button
                          onClick={() => navigate("/me/blocked-users")}
                          className={`w-full flex items-center justify-between p-4 ${getThemeClasses("bg-muted")} hover:bg-gray-100 rounded-lg border ${getThemeClasses("border-secondary")} transition-colors`}
                          aria-label="Manage blocked users"
                        >
                          <div className="flex items-center">
                            <NoSymbolIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mr-3`} aria-hidden="true" />
                            <div className="text-left">
                              <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                Blocked Users
                              </p>
                              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                                Manage users who cannot share folders with you
                              </p>
                            </div>
                          </div>
                          <ChevronRightIcon className={`h-5 w-5 ${getThemeClasses("text-muted")}`} aria-hidden="true" />
                        </button>
                      </div>

                      {/* Data Export Section (GDPR Article 20) */}
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border ${getThemeClasses("border-secondary")} p-6`}>
                        <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                          Data Export
                        </h3>
                        <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
                          Download a copy of your data in accordance with GDPR
                          Article 20.
                        </p>
                        <button
                          onClick={() => navigate("/me/export-data")}
                          className={`w-full flex items-center justify-between p-4 ${getThemeClasses("bg-muted")} hover:bg-gray-100 rounded-lg border ${getThemeClasses("border-secondary")} transition-colors`}
                          aria-label="Export your data"
                        >
                          <div className="flex items-center">
                            <ArrowDownTrayIcon className={`h-5 w-5 ${getThemeClasses("text-muted")} mr-3`} aria-hidden="true" />
                            <div className="text-left">
                              <p className={`font-medium ${getThemeClasses("text-primary")}`}>
                                Export Your Data
                              </p>
                              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                                Request a complete copy of your account data
                              </p>
                            </div>
                          </div>
                          <ChevronRightIcon className={`h-5 w-5 ${getThemeClasses("text-muted")}`} aria-hidden="true" />
                        </button>
                      </div>

                      {/* Danger Zone */}
                      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-lg border-2 border-red-200 p-6`}>
                        <h3 className="text-lg font-semibold text-red-900 mb-2 flex items-center">
                          <ExclamationTriangleIcon className="h-5 w-5 mr-2" aria-hidden="true" />
                          Danger Zone
                        </h3>
                        <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
                          Permanently delete your account and all associated data.
                          This action cannot be undone and complies with GDPR
                          Article 17.
                        </p>
                        <Button
                          onClick={() => navigate("/me/delete-account")}
                          variant="danger"
                          icon={TrashIcon}
                        >
                          Delete My Account
                        </Button>
                      </div>
                    </div>
                  )}

                  {/* Tags Tab - redirects to /me/tags */}
                </div>
              </div>
            )}
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default withPasswordProtection(MeDetail);
