// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/Me/MeDetail.jsx
import { useState, useEffect } from "react";
import { Link, useSearchParams } from "react-router-dom";
import Navigation from "../../../components/Navigation";
import Page from "../../../components/Page";
import TagsList from "../Tags/TagsList";
import {
  GetUserProfile,
  UpdateUserProfile,
  SelectExportDirectory,
  GetExportEstimate,
  CreateExportDirectory,
  ExportUserProfile,
  ExportCollections,
  ExportAllFilesMetadata,
  ExportAllFiles,
  OpenExportFolder,
} from "../../../../wailsjs/go/app/Application";
import "../Dashboard/Dashboard.css";

function MeDetail() {
  const [searchParams] = useSearchParams();
  const initialTab = searchParams.get("tab") || "profile";

  const [userProfile, setUserProfile] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [activeTab, setActiveTab] = useState(initialTab);

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

  // Export-related state
  const EXPORT_STEPS = {
    WELCOME: 0,
    PROFILE: 1,
    COLLECTIONS: 2,
    FILE_METADATA: 3,
    FILE_CONTENTS: 4,
    SUMMARY: 5,
  };

  const [exportStep, setExportStep] = useState(EXPORT_STEPS.WELCOME);
  const [exportLoading, setExportLoading] = useState(false);
  const [exportError, setExportError] = useState("");
  const [exportPath, setExportPath] = useState("");
  const [exportEstimate, setExportEstimate] = useState(null);
  const [profileExport, setProfileExport] = useState(null);
  const [collectionsExport, setCollectionsExport] = useState(null);
  const [filesMetadataExport, setFilesMetadataExport] = useState(null);
  const [exportSummary, setExportSummary] = useState(null);
  const [exportProgress, setExportProgress] = useState({
    current: 0,
    total: 0,
    currentFile: "",
    status: "",
  });
  const [exportCompletedSteps, setExportCompletedSteps] = useState({
    0: false,
    1: false,
    2: false,
    3: false,
    4: false,
  });

  // 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" },
  ];

  useEffect(() => {
    // Wait for Wails runtime to be ready
    let attempts = 0;
    const maxAttempts = 50;
    let isCancelled = false;

    const checkWailsReady = () => {
      if (isCancelled) return;

      if (window.go && window.go.app && window.go.app.Application) {
        loadUserProfile();
        // If export tab is requested via URL, load the estimate
        if (initialTab === "export") {
          loadExportEstimate();
        }
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkWailsReady, 100);
      } else {
        if (!isCancelled) {
          setIsLoading(false);
          setError("Failed to initialize. Please refresh the page.");
        }
      }
    };

    checkWailsReady();

    return () => {
      isCancelled = true;
    };
  }, [initialTab]);

  const loadUserProfile = async () => {
    try {
      setIsLoading(true);
      setError("");

      if (!window.go || !window.go.app || !window.go.app.Application) {
        throw new Error("Application not ready");
      }

      console.log("Fetching user profile...");
      const profile = await GetUserProfile();
      console.log("Profile received:", profile);

      setUserProfile(profile);
      setFormData({
        email: profile.email || "",
        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,
      });
    } catch (err) {
      console.error("Failed to load profile:", err);
      setError(err.message || "Failed to load profile");
    } finally {
      setIsLoading(false);
    }
  };

  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 {
      console.log("Updating profile with:", formData);
      const updatedProfile = await UpdateUserProfile(formData);
      console.log("Profile updated:", updatedProfile);

      setUserProfile(updatedProfile);
      setIsEditing(false);
    } catch (err) {
      console.error("Failed to update profile:", err);
      setEditError(err.message || "Failed to update profile");
    } finally {
      setEditLoading(false);
    }
  };

  const handleCancelEdit = () => {
    if (userProfile) {
      setFormData({
        email: userProfile.email || "",
        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("");
  };

  // Export Functions
  const loadExportEstimate = async () => {
    try {
      setExportLoading(true);
      const est = await GetExportEstimate();
      setExportEstimate(est);
    } catch (err) {
      console.error("Failed to get export estimate:", err);
      setExportError(err.message || "Failed to get export estimate");
    } finally {
      setExportLoading(false);
    }
  };

  const handleSelectExportDirectory = async () => {
    try {
      setExportError("");
      const path = await SelectExportDirectory();
      if (path) {
        setExportPath(path);
      }
    } catch (err) {
      console.error("Failed to select directory:", err);
      setExportError(err.message || "Failed to select directory");
    }
  };

  const handleStartExport = async () => {
    if (!exportPath) {
      setExportError("Please select an export directory first");
      return;
    }

    try {
      setExportLoading(true);
      setExportError("");

      const finalPath = await CreateExportDirectory(exportPath);
      setExportPath(finalPath);

      setExportCompletedSteps(prev => ({ ...prev, [EXPORT_STEPS.WELCOME]: true }));
      setExportStep(EXPORT_STEPS.PROFILE);
    } catch (err) {
      console.error("Failed to create export directory:", err);
      setExportError(err.message || "Failed to create export directory");
    } finally {
      setExportLoading(false);
    }
  };

  const handleExportProfile = async () => {
    try {
      setExportLoading(true);
      setExportError("");

      const profile = await ExportUserProfile(exportPath);
      setProfileExport(profile);

      setExportCompletedSteps(prev => ({ ...prev, [EXPORT_STEPS.PROFILE]: true }));
      setExportStep(EXPORT_STEPS.COLLECTIONS);
    } catch (err) {
      console.error("Failed to export profile:", err);
      setExportError(err.message || "Failed to export profile");
    } finally {
      setExportLoading(false);
    }
  };

  const handleExportCollections = async () => {
    try {
      setExportLoading(true);
      setExportError("");

      const collections = await ExportCollections(exportPath);
      setCollectionsExport(collections);

      setExportCompletedSteps(prev => ({ ...prev, [EXPORT_STEPS.COLLECTIONS]: true }));
      setExportStep(EXPORT_STEPS.FILE_METADATA);
    } catch (err) {
      console.error("Failed to export collections:", err);
      setExportError(err.message || "Failed to export collections");
    } finally {
      setExportLoading(false);
    }
  };

  const handleExportFileMetadata = async () => {
    try {
      setExportLoading(true);
      setExportError("");

      const metadata = await ExportAllFilesMetadata(exportPath);
      setFilesMetadataExport(metadata);

      setExportCompletedSteps(prev => ({ ...prev, [EXPORT_STEPS.FILE_METADATA]: true }));
      setExportStep(EXPORT_STEPS.FILE_CONTENTS);
    } catch (err) {
      console.error("Failed to export file metadata:", err);
      setExportError(err.message || "Failed to export file metadata");
    } finally {
      setExportLoading(false);
    }
  };

  const handleExportFileContents = async () => {
    try {
      setExportLoading(true);
      setExportError("");
      setExportProgress({ current: 0, total: 0, currentFile: "", status: "Starting export..." });

      const summary = await ExportAllFiles(exportPath, null);
      setExportSummary(summary);

      setExportCompletedSteps(prev => ({ ...prev, [EXPORT_STEPS.FILE_CONTENTS]: true }));
      setExportStep(EXPORT_STEPS.SUMMARY);
    } catch (err) {
      console.error("Failed to export files:", err);
      setExportError(err.message || "Failed to export files");
    } finally {
      setExportLoading(false);
    }
  };

  const handleOpenExportFolder = async () => {
    try {
      await OpenExportFolder(exportPath);
    } catch (err) {
      console.error("Failed to open export folder:", err);
      setExportError(err.message || "Failed to open export folder");
    }
  };

  const resetExport = () => {
    setExportStep(EXPORT_STEPS.WELCOME);
    setExportLoading(false);
    setExportError("");
    setExportPath("");
    setExportEstimate(null);
    setProfileExport(null);
    setCollectionsExport(null);
    setFilesMetadataExport(null);
    setExportSummary(null);
    setExportProgress({ current: 0, total: 0, currentFile: "", status: "" });
    setExportCompletedSteps({ 0: false, 1: false, 2: false, 3: false, 4: false });
  };

  const formatBytes = (bytes) => {
    if (!bytes || bytes === 0) return "0 B";
    const k = 1024;
    const sizes = ["B", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  const formatDate = (dateString) => {
    if (!dateString) return "N/A";
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return "Invalid Date";
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });
    } catch (error) {
      return "Invalid Date";
    }
  };

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

  if (isLoading) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="My Profile">
            <div style={{ textAlign: "center", padding: "40px" }}>
              <p>Loading your profile...</p>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  if (error && !userProfile) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="My Profile">
            <div style={{ padding: "20px", color: "#e74c3c" }}>
              <h3>Error Loading Profile</h3>
              <p>{error}</p>
              <button onClick={loadUserProfile} className="nav-button">
                Try Again
              </button>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  if (!userProfile) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="My Profile">
            <p>No profile data available.</p>
          </Page>
        </div>
      </div>
    );
  }

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="My Account">
          {/* Header */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "30px" }}>
            <div>
              <h2 style={{ margin: 0 }}>Account Settings</h2>
              <p style={{ color: "#7f8c8d", margin: "5px 0 0 0" }}>
                Manage your profile and preferences
              </p>
            </div>
            <button onClick={() => loadUserProfile()} className="nav-button secondary">
              Refresh
            </button>
          </div>

          {/* Tabs */}
          <div style={{ display: "flex", gap: "10px", marginBottom: "20px", borderBottom: "2px solid #ecf0f1" }}>
            <button
              onClick={() => setActiveTab("profile")}
              className={activeTab === "profile" ? "nav-button" : "nav-button secondary"}
              style={{ borderRadius: "8px 8px 0 0" }}
            >
              Profile
            </button>
            <button
              onClick={() => setActiveTab("security")}
              className={activeTab === "security" ? "nav-button" : "nav-button secondary"}
              style={{ borderRadius: "8px 8px 0 0" }}
            >
              Security
            </button>
            <button
              onClick={() => setActiveTab("tags")}
              className={activeTab === "tags" ? "nav-button" : "nav-button secondary"}
              style={{ borderRadius: "8px 8px 0 0" }}
            >
              Tags
            </button>
            <button
              onClick={() => {
                setActiveTab("export");
                if (!exportEstimate) {
                  loadExportEstimate();
                }
              }}
              className={activeTab === "export" ? "nav-button" : "nav-button secondary"}
              style={{ borderRadius: "8px 8px 0 0" }}
            >
              Export All Data
            </button>
          </div>

          {/* Profile Tab */}
          {activeTab === "profile" && (
            <div>
              {/* User Avatar/Header */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                marginBottom: "20px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
                textAlign: "center",
              }}>
                <div style={{
                  width: "100px",
                  height: "100px",
                  borderRadius: "50%",
                  background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                  color: "white",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: "36px",
                  fontWeight: "bold",
                  margin: "0 auto 20px",
                }}>
                  {userProfile.first_name?.charAt(0)}{userProfile.last_name?.charAt(0)}
                </div>
                <h2 style={{ margin: "0 0 5px 0", color: "#2c3e50" }}>
                  {userProfile.first_name} {userProfile.last_name}
                </h2>
                <p style={{ color: "#7f8c8d", margin: 0 }}>{userProfile.email}</p>
                <div style={{
                  display: "inline-block",
                  background: "#27ae60",
                  color: "white",
                  padding: "4px 12px",
                  borderRadius: "12px",
                  fontSize: "12px",
                  marginTop: "10px",
                }}>
                  ✓ Verified User
                </div>
              </div>

              {/* Personal Information */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                marginBottom: "20px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
                  <h3 style={{ margin: 0, color: "#2c3e50" }}>Personal Information</h3>
                  {!isEditing && (
                    <button onClick={() => setIsEditing(true)} className="nav-button secondary">
                      ✏️ Edit Profile
                    </button>
                  )}
                </div>

                {isEditing ? (
                  <form onSubmit={handleSaveChanges} style={{ display: "flex", flexDirection: "column", gap: "15px" }}>
                    {editError && (
                      <div style={{ padding: "12px", background: "#fee", border: "1px solid #fcc", borderRadius: "6px", color: "#c33" }}>
                        {editError}
                      </div>
                    )}

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "15px" }}>
                      <div>
                        <label style={{ display: "block", marginBottom: "5px", fontWeight: "500", color: "#2c3e50" }}>First Name</label>
                        <input
                          name="first_name"
                          type="text"
                          value={formData.first_name}
                          onChange={handleInputChange}
                          style={{ width: "100%", padding: "8px", borderRadius: "6px", border: "1px solid #ddd" }}
                          disabled={editLoading}
                          required
                        />
                      </div>
                      <div>
                        <label style={{ display: "block", marginBottom: "5px", fontWeight: "500", color: "#2c3e50" }}>Last Name</label>
                        <input
                          name="last_name"
                          type="text"
                          value={formData.last_name}
                          onChange={handleInputChange}
                          style={{ width: "100%", padding: "8px", borderRadius: "6px", border: "1px solid #ddd" }}
                          disabled={editLoading}
                          required
                        />
                      </div>
                      <div>
                        <label style={{ display: "block", marginBottom: "5px", fontWeight: "500", color: "#2c3e50" }}>Email</label>
                        <input
                          name="email"
                          type="email"
                          value={formData.email}
                          onChange={handleInputChange}
                          style={{ width: "100%", padding: "8px", borderRadius: "6px", border: "1px solid #ddd" }}
                          disabled={editLoading}
                          required
                        />
                      </div>
                      <div>
                        <label style={{ display: "block", marginBottom: "5px", fontWeight: "500", color: "#2c3e50" }}>Phone</label>
                        <input
                          name="phone"
                          type="tel"
                          value={formData.phone}
                          onChange={handleInputChange}
                          style={{ width: "100%", padding: "8px", borderRadius: "6px", border: "1px solid #ddd" }}
                          disabled={editLoading}
                        />
                      </div>
                      <div>
                        <label style={{ display: "block", marginBottom: "5px", fontWeight: "500", color: "#2c3e50" }}>Country</label>
                        <select
                          name="country"
                          value={formData.country}
                          onChange={handleInputChange}
                          style={{ width: "100%", padding: "8px", borderRadius: "6px", border: "1px solid #ddd" }}
                          disabled={editLoading}
                        >
                          {countries.map((c) => (
                            <option key={c} value={c}>{c}</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label style={{ display: "block", marginBottom: "5px", fontWeight: "500", color: "#2c3e50" }}>Timezone</label>
                        <select
                          name="timezone"
                          value={formData.timezone}
                          onChange={handleInputChange}
                          style={{ width: "100%", padding: "8px", borderRadius: "6px", border: "1px solid #ddd" }}
                          disabled={editLoading}
                        >
                          {timezones.map((tz) => (
                            <option key={tz.value} value={tz.value}>{tz.label}</option>
                          ))}
                        </select>
                      </div>
                    </div>

                    <div style={{ display: "flex", justifyContent: "flex-end", gap: "10px", marginTop: "10px" }}>
                      <button
                        type="button"
                        onClick={handleCancelEdit}
                        className="nav-button secondary"
                        disabled={editLoading}
                      >
                        Cancel
                      </button>
                      <button
                        type="submit"
                        className="nav-button success"
                        disabled={editLoading}
                      >
                        {editLoading ? "Saving..." : "Save Changes"}
                      </button>
                    </div>
                  </form>
                ) : (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
                    <div>
                      <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Full Name</p>
                      <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{userProfile.first_name} {userProfile.last_name}</p>
                    </div>
                    <div>
                      <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Email</p>
                      <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{userProfile.email}</p>
                    </div>
                    <div>
                      <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Phone</p>
                      <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{userProfile.phone || "N/A"}</p>
                    </div>
                    <div>
                      <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Country</p>
                      <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{userProfile.country || "N/A"}</p>
                    </div>
                    <div>
                      <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Timezone</p>
                      <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{userProfile.timezone || "N/A"}</p>
                    </div>
                    <div>
                      <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Member Since</p>
                      <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{formatDate(userProfile.created_at)}</p>
                    </div>
                  </div>
                )}
              </div>

              {/* Account Information */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}>
                <h3 style={{ marginTop: 0, color: "#2c3e50" }}>Account Information</h3>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
                  <div>
                    <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>User ID</p>
                    <p style={{ margin: 0, fontFamily: "monospace", fontSize: "13px", color: "#2c3e50" }}>{userProfile.id}</p>
                  </div>
                  <div>
                    <p style={{ color: "#7f8c8d", fontSize: "14px", margin: "0 0 5px 0" }}>Account Type</p>
                    <p style={{ margin: 0, fontWeight: "500", color: "#2c3e50" }}>{getRoleText(userProfile.role)}</p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Security Tab */}
          {activeTab === "security" && (
            <div>
              {/* Security Settings */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                marginBottom: "20px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}>
                <h3 style={{ marginTop: 0, color: "#2c3e50" }}>Security Settings</h3>
                <div style={{ display: "flex", flexDirection: "column", gap: "15px" }}>
                  <div style={{ padding: "15px", background: "#d4edda", border: "1px solid #c3e6cb", borderRadius: "6px" }}>
                    <div style={{ display: "flex", alignItems: "start" }}>
                      <span style={{ fontSize: "20px", marginRight: "10px" }}>✓</span>
                      <div>
                        <h4 style={{ margin: "0 0 5px 0", color: "#155724" }}>Two-Factor Authentication</h4>
                        <p style={{ margin: 0, fontSize: "14px", color: "#155724" }}>
                          Your account is protected with 2FA (managed at the identity provider level).
                        </p>
                      </div>
                    </div>
                  </div>
                  <div style={{ padding: "15px", background: "#d1ecf1", border: "1px solid #bee5eb", borderRadius: "6px" }}>
                    <div style={{ display: "flex", alignItems: "start" }}>
                      <span style={{ fontSize: "20px", marginRight: "10px" }}>🔒</span>
                      <div>
                        <h4 style={{ margin: "0 0 5px 0", color: "#0c5460" }}>End-to-End Encryption</h4>
                        <p style={{ margin: 0, fontSize: "14px", color: "#0c5460" }}>
                          All your files are encrypted with your keys before they leave your device.
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Notification Preferences */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                marginBottom: "20px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}>
                <h3 style={{ marginTop: 0, color: "#2c3e50" }}>Notification Preferences</h3>
                <p style={{ color: "#7f8c8d", fontSize: "14px" }}>
                  Control how you receive notifications from MapleFile.
                </p>
                <div style={{ marginTop: "15px" }}>
                  <label style={{ display: "flex", alignItems: "center", cursor: "pointer" }}>
                    <input
                      type="checkbox"
                      checked={formData.share_notifications_enabled}
                      onChange={async (e) => {
                        const newValue = e.target.checked;
                        setFormData((prev) => ({
                          ...prev,
                          share_notifications_enabled: newValue,
                        }));
                        try {
                          const updatedProfile = await UpdateUserProfile({
                            ...formData,
                            share_notifications_enabled: newValue,
                          });
                          setUserProfile(updatedProfile);
                        } catch (err) {
                          console.error("Failed to update notification preference:", err);
                          // Revert on error
                          setFormData((prev) => ({
                            ...prev,
                            share_notifications_enabled: !newValue,
                          }));
                        }
                      }}
                      style={{ marginRight: "10px", width: "18px", height: "18px" }}
                    />
                    <div>
                      <div style={{ fontWeight: "500", color: "#2c3e50" }}>Share Notifications</div>
                      <div style={{ fontSize: "14px", color: "#7f8c8d" }}>
                        Receive email notifications when someone shares a collection with you
                      </div>
                    </div>
                  </label>
                </div>
              </div>

              {/* Privacy Settings */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                marginBottom: "20px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}>
                <h3 style={{ marginTop: 0, color: "#2c3e50" }}>Privacy Settings</h3>
                <Link
                  to="/me/blocked-users"
                  className="nav-button secondary"
                  style={{ display: "inline-flex", alignItems: "center", textDecoration: "none" }}
                >
                  🚫 Manage Blocked Users
                </Link>
              </div>

              {/* Danger Zone */}
              <div style={{
                background: "white",
                padding: "30px",
                borderRadius: "12px",
                border: "2px solid #fee",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
              }}>
                <h3 style={{ marginTop: 0, color: "#e74c3c", display: "flex", alignItems: "center" }}>
                  Danger Zone
                </h3>
                <p style={{ color: "#7f8c8d" }}>
                  Permanently delete your account and all associated data. This action cannot be undone.
                </p>
                <Link
                  to="/me/delete-account"
                  className="nav-button danger"
                  style={{ textDecoration: "none" }}
                >
                  Delete My Account
                </Link>
              </div>
            </div>
          )}

          {/* Export Tab */}
          {activeTab === "export" && (
            <div>
              {/* Export Error Display */}
              {exportError && (
                <div style={{
                  padding: "15px",
                  background: "#ffebee",
                  color: "#c62828",
                  borderRadius: "4px",
                  marginBottom: "20px",
                  border: "1px solid #f44336",
                }}>
                  {exportError}
                  <button
                    onClick={() => setExportError("")}
                    style={{
                      float: "right",
                      background: "none",
                      border: "none",
                      color: "#c62828",
                      cursor: "pointer",
                      fontWeight: "bold",
                    }}
                  >
                    x
                  </button>
                </div>
              )}

              {/* Step Indicator */}
              <div style={{
                display: "flex",
                justifyContent: "center",
                marginBottom: "30px",
                flexWrap: "wrap",
                gap: "10px",
              }}>
                {["Welcome", "Profile", "Collections", "Metadata", "Files", "Summary"].map((name, index) => (
                  <div key={index} style={{ display: "flex", alignItems: "center" }}>
                    <div style={{
                      width: "32px",
                      height: "32px",
                      borderRadius: "50%",
                      background: exportStep === index ? "#3498db" :
                                 exportCompletedSteps[index] ? "#27ae60" : "#bdc3c7",
                      color: "white",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontWeight: "bold",
                      fontSize: "14px",
                    }}>
                      {exportCompletedSteps[index] ? "✓" : index + 1}
                    </div>
                    <span style={{
                      marginLeft: "8px",
                      color: exportStep === index ? "#3498db" : "#7f8c8d",
                      fontWeight: exportStep === index ? "bold" : "normal",
                      fontSize: "14px",
                    }}>
                      {name}
                    </span>
                    {index < 5 && (
                      <div style={{
                        width: "30px",
                        height: "2px",
                        background: exportCompletedSteps[index] ? "#27ae60" : "#bdc3c7",
                        marginLeft: "10px",
                      }} />
                    )}
                  </div>
                ))}
              </div>

              {/* Step Content */}
              <div style={{
                background: "white",
                borderRadius: "8px",
                padding: "40px",
                boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
                minHeight: "400px",
              }}>
                {/* WELCOME Step */}
                {exportStep === EXPORT_STEPS.WELCOME && (
                  <div style={{ textAlign: "center" }}>
                    <h2 style={{ marginBottom: "20px", color: "#2c3e50" }}>Export All Your Data</h2>
                    <p style={{ color: "#666", marginBottom: "30px", maxWidth: "600px", margin: "0 auto 30px" }}>
                      This wizard will guide you through exporting all your MapleFile data,
                      including your profile, collections, file metadata, and all file contents.
                      Your files will be decrypted and saved to your chosen location.
                    </p>

                    {exportEstimate && (
                      <div style={{
                        background: "#f8f9fa",
                        borderRadius: "8px",
                        padding: "20px",
                        marginBottom: "30px",
                        textAlign: "left",
                        maxWidth: "500px",
                        margin: "0 auto 30px",
                      }}>
                        <h4 style={{ marginBottom: "15px", color: "#2c3e50" }}>Export Summary</h4>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px" }}>
                          <div>
                            <span style={{ color: "#666" }}>Total Collections:</span>
                            <strong style={{ marginLeft: "10px", color: "#2c3e50" }}>{exportEstimate.total_collections}</strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Owned:</span>
                            <strong style={{ marginLeft: "10px", color: "#2c3e50" }}>{exportEstimate.owned_collections}</strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Shared:</span>
                            <strong style={{ marginLeft: "10px", color: "#2c3e50" }}>{exportEstimate.shared_collections}</strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Total Files:</span>
                            <strong style={{ marginLeft: "10px", color: "#2c3e50" }}>{exportEstimate.total_files}</strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Local Files:</span>
                            <strong style={{ marginLeft: "10px", color: "#27ae60" }}>{exportEstimate.local_files_count}</strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Cloud Only:</span>
                            <strong style={{ marginLeft: "10px", color: "#e67e22" }}>{exportEstimate.cloud_only_count}</strong>
                          </div>
                          <div style={{ gridColumn: "span 2" }}>
                            <span style={{ color: "#666" }}>Estimated Time:</span>
                            <strong style={{ marginLeft: "10px", color: "#2c3e50" }}>{exportEstimate.estimated_time}</strong>
                          </div>
                        </div>
                      </div>
                    )}

                    <div style={{ marginBottom: "20px" }}>
                      <label style={{ display: "block", marginBottom: "10px", fontWeight: "bold", color: "#2c3e50" }}>
                        Select Export Location:
                      </label>
                      <div style={{ display: "flex", gap: "10px", justifyContent: "center", alignItems: "center" }}>
                        <input
                          type="text"
                          value={exportPath}
                          readOnly
                          placeholder="Click 'Browse' to select a folder"
                          style={{
                            padding: "10px 15px",
                            border: "1px solid #ddd",
                            borderRadius: "4px",
                            width: "300px",
                            background: "#f8f9fa",
                            color: "#2c3e50",
                          }}
                        />
                        <button
                          onClick={handleSelectExportDirectory}
                          className="nav-button"
                          style={{ margin: 0 }}
                        >
                          Browse...
                        </button>
                      </div>
                    </div>

                    <button
                      onClick={handleStartExport}
                      disabled={!exportPath || exportLoading}
                      className="nav-button success"
                      style={{
                        padding: "15px 40px",
                        fontSize: "16px",
                        opacity: !exportPath || exportLoading ? 0.5 : 1,
                      }}
                    >
                      {exportLoading ? "Creating export folder..." : "Start Export"}
                    </button>
                  </div>
                )}

                {/* PROFILE Step */}
                {exportStep === EXPORT_STEPS.PROFILE && (
                  <div style={{ textAlign: "center" }}>
                    <h2 style={{ marginBottom: "20px", color: "#2c3e50" }}>Step 2: Export User Profile</h2>
                    <p style={{ color: "#666", marginBottom: "30px" }}>
                      Export your user profile information including name, email, and preferences.
                    </p>

                    {profileExport ? (
                      <div style={{
                        background: "#e8f5e9",
                        borderRadius: "8px",
                        padding: "20px",
                        marginBottom: "30px",
                        maxWidth: "400px",
                        margin: "0 auto 30px",
                      }}>
                        <div style={{ fontSize: "48px", marginBottom: "10px" }}>✓</div>
                        <h4 style={{ color: "#27ae60" }}>Profile Exported Successfully</h4>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          Saved as profile.json
                        </p>
                      </div>
                    ) : (
                      <button
                        onClick={handleExportProfile}
                        disabled={exportLoading}
                        className="nav-button success"
                        style={{ padding: "15px 40px", fontSize: "16px" }}
                      >
                        {exportLoading ? "Exporting..." : "Export Profile"}
                      </button>
                    )}
                  </div>
                )}

                {/* COLLECTIONS Step */}
                {exportStep === EXPORT_STEPS.COLLECTIONS && (
                  <div style={{ textAlign: "center" }}>
                    <h2 style={{ marginBottom: "20px", color: "#2c3e50" }}>Step 3: Export Collections</h2>
                    <p style={{ color: "#666", marginBottom: "30px" }}>
                      Export all your collections (owned and shared) with decrypted names.
                    </p>

                    {collectionsExport ? (
                      <div style={{
                        background: "#e8f5e9",
                        borderRadius: "8px",
                        padding: "20px",
                        marginBottom: "30px",
                        maxWidth: "400px",
                        margin: "0 auto 30px",
                      }}>
                        <div style={{ fontSize: "48px", marginBottom: "10px" }}>✓</div>
                        <h4 style={{ color: "#27ae60" }}>Collections Exported Successfully</h4>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          {collectionsExport.total_count} collections exported
                        </p>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          Saved as collections.json
                        </p>
                      </div>
                    ) : (
                      <button
                        onClick={handleExportCollections}
                        disabled={exportLoading}
                        className="nav-button success"
                        style={{ padding: "15px 40px", fontSize: "16px" }}
                      >
                        {exportLoading ? "Exporting..." : "Export Collections"}
                      </button>
                    )}
                  </div>
                )}

                {/* FILE_METADATA Step */}
                {exportStep === EXPORT_STEPS.FILE_METADATA && (
                  <div style={{ textAlign: "center" }}>
                    <h2 style={{ marginBottom: "20px", color: "#2c3e50" }}>Step 4: Export File Metadata</h2>
                    <p style={{ color: "#666", marginBottom: "30px" }}>
                      Export metadata for all files (filenames, sizes, types) without downloading content yet.
                    </p>

                    {filesMetadataExport ? (
                      <div style={{
                        background: "#e8f5e9",
                        borderRadius: "8px",
                        padding: "20px",
                        marginBottom: "30px",
                        maxWidth: "400px",
                        margin: "0 auto 30px",
                      }}>
                        <div style={{ fontSize: "48px", marginBottom: "10px" }}>✓</div>
                        <h4 style={{ color: "#27ae60" }}>File Metadata Exported Successfully</h4>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          {filesMetadataExport.total_count} files indexed
                        </p>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          Total size: {formatBytes(filesMetadataExport.total_size_bytes)}
                        </p>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          Saved as files_metadata.json
                        </p>
                      </div>
                    ) : (
                      <button
                        onClick={handleExportFileMetadata}
                        disabled={exportLoading}
                        className="nav-button success"
                        style={{ padding: "15px 40px", fontSize: "16px" }}
                      >
                        {exportLoading ? "Exporting..." : "Export File Metadata"}
                      </button>
                    )}
                  </div>
                )}

                {/* FILE_CONTENTS Step */}
                {exportStep === EXPORT_STEPS.FILE_CONTENTS && (
                  <div style={{ textAlign: "center" }}>
                    <h2 style={{ marginBottom: "20px", color: "#2c3e50" }}>Step 5: Export File Contents</h2>
                    <p style={{ color: "#666", marginBottom: "30px" }}>
                      Download and decrypt all file contents. Local files will be copied,
                      cloud-only files will be downloaded.
                    </p>

                    {exportLoading && (
                      <div style={{
                        background: "#fff3cd",
                        borderRadius: "8px",
                        padding: "20px",
                        marginBottom: "30px",
                        maxWidth: "500px",
                        margin: "0 auto 30px",
                      }}>
                        <div style={{ fontSize: "36px", marginBottom: "10px" }}>
                          <span style={{
                            display: "inline-block",
                            animation: "spin 1s linear infinite",
                          }}>...</span>
                        </div>
                        <h4 style={{ color: "#2c3e50" }}>Exporting Files...</h4>
                        <p style={{ fontSize: "14px", color: "#666" }}>
                          {exportProgress.status || "Please wait while your files are being exported..."}
                        </p>
                        <p style={{ fontSize: "12px", color: "#856404", marginTop: "10px" }}>
                          This may take a while depending on the number and size of your files.
                        </p>
                      </div>
                    )}

                    {!exportLoading && !exportSummary && (
                      <div>
                        <div style={{
                          background: "#e3f2fd",
                          borderRadius: "8px",
                          padding: "20px",
                          marginBottom: "30px",
                          maxWidth: "500px",
                          margin: "0 auto 30px",
                          textAlign: "left",
                        }}>
                          <h4 style={{ marginBottom: "10px", color: "#2c3e50" }}>What will happen:</h4>
                          <ul style={{ paddingLeft: "20px", color: "#666" }}>
                            <li>Files available locally will be copied directly</li>
                            <li>Cloud-only files will be downloaded and decrypted</li>
                            <li>Files will be organized into collection folders</li>
                            <li>Errors will be logged but won't stop the export</li>
                          </ul>
                        </div>

                        <button
                          onClick={handleExportFileContents}
                          className="nav-button success"
                          style={{ padding: "15px 40px", fontSize: "16px" }}
                        >
                          Start File Export
                        </button>
                      </div>
                    )}
                  </div>
                )}

                {/* SUMMARY Step */}
                {exportStep === EXPORT_STEPS.SUMMARY && (
                  <div style={{ textAlign: "center" }}>
                    <h2 style={{ marginBottom: "20px", color: "#2c3e50" }}>Export Complete!</h2>

                    {exportSummary && (
                      <div style={{
                        background: exportSummary.files_failed > 0 ? "#fff3cd" : "#e8f5e9",
                        borderRadius: "8px",
                        padding: "30px",
                        marginBottom: "30px",
                        maxWidth: "600px",
                        margin: "0 auto 30px",
                        textAlign: "left",
                      }}>
                        <div style={{ textAlign: "center", marginBottom: "20px" }}>
                          <div style={{ fontSize: "64px" }}>
                            {exportSummary.files_failed > 0 ? "!" : "✓"}
                          </div>
                          <h3 style={{ color: exportSummary.files_failed > 0 ? "#856404" : "#27ae60" }}>
                            {exportSummary.files_failed > 0
                              ? "Export Completed with Some Errors"
                              : "All Data Exported Successfully!"}
                          </h3>
                        </div>

                        <div style={{
                          display: "grid",
                          gridTemplateColumns: "1fr 1fr",
                          gap: "15px",
                          background: "white",
                          padding: "20px",
                          borderRadius: "8px",
                        }}>
                          <div>
                            <span style={{ color: "#666" }}>Collections:</span>
                            <strong style={{ display: "block", fontSize: "20px", color: "#2c3e50" }}>
                              {exportSummary.total_collections}
                            </strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Files Exported:</span>
                            <strong style={{ display: "block", fontSize: "20px", color: "#2c3e50" }}>
                              {exportSummary.files_exported}
                            </strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Copied from Local:</span>
                            <strong style={{ display: "block", fontSize: "20px", color: "#27ae60" }}>
                              {exportSummary.files_copied_local}
                            </strong>
                          </div>
                          <div>
                            <span style={{ color: "#666" }}>Downloaded from Cloud:</span>
                            <strong style={{ display: "block", fontSize: "20px", color: "#3498db" }}>
                              {exportSummary.files_downloaded}
                            </strong>
                          </div>
                          {exportSummary.files_failed > 0 && (
                            <div style={{ gridColumn: "span 2" }}>
                              <span style={{ color: "#dc3545" }}>Files Failed:</span>
                              <strong style={{ display: "block", fontSize: "20px", color: "#dc3545" }}>
                                {exportSummary.files_failed}
                              </strong>
                            </div>
                          )}
                          <div style={{ gridColumn: "span 2" }}>
                            <span style={{ color: "#666" }}>Total Size:</span>
                            <strong style={{ display: "block", fontSize: "20px", color: "#2c3e50" }}>
                              {formatBytes(exportSummary.total_size_bytes)}
                            </strong>
                          </div>
                        </div>

                        {exportSummary.errors && exportSummary.errors.length > 0 && (
                          <div style={{
                            marginTop: "20px",
                            background: "#ffebee",
                            padding: "15px",
                            borderRadius: "8px",
                          }}>
                            <h4 style={{ color: "#c62828", marginBottom: "10px" }}>
                              Errors ({exportSummary.errors.length}):
                            </h4>
                            <div style={{
                              maxHeight: "150px",
                              overflowY: "auto",
                              fontSize: "12px",
                              color: "#2c3e50",
                            }}>
                              {exportSummary.errors.map((err, idx) => (
                                <div key={idx} style={{
                                  padding: "5px 0",
                                  borderBottom: idx < exportSummary.errors.length - 1 ? "1px solid #ffcdd2" : "none",
                                }}>
                                  <strong>{err.filename}</strong>: {err.error_message}
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        <div style={{
                          marginTop: "20px",
                          padding: "15px",
                          background: "#f8f9fa",
                          borderRadius: "8px",
                        }}>
                          <span style={{ color: "#666" }}>Export Location:</span>
                          <p style={{
                            fontFamily: "monospace",
                            fontSize: "12px",
                            wordBreak: "break-all",
                            margin: "5px 0 0",
                            color: "#2c3e50",
                          }}>
                            {exportPath}
                          </p>
                        </div>
                      </div>
                    )}

                    <div style={{ display: "flex", gap: "15px", justifyContent: "center" }}>
                      <button
                        onClick={handleOpenExportFolder}
                        className="nav-button success"
                        style={{ padding: "15px 30px" }}
                      >
                        Open Export Folder
                      </button>
                      <button
                        onClick={resetExport}
                        className="nav-button"
                        style={{ padding: "15px 30px" }}
                      >
                        Start New Export
                      </button>
                    </div>
                  </div>
                )}
              </div>

              {/* CSS for spinner animation */}
              <style>{`
                @keyframes spin {
                  from { transform: rotate(0deg); }
                  to { transform: rotate(360deg); }
                }
              `}</style>
            </div>
          )}

          {/* Tags Tab */}
          {activeTab === "tags" && (
            <div>
              <TagsList />
            </div>
          )}
        </Page>
      </div>
    </div>
  );
}

export default MeDetail;
