"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/contexts/supabase-auth-context";
import { useRouter } from "next/navigation";
import { swal } from "@/lib/sweetalert";
import Link from "next/link";

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button, buttonVariants } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Label } from "@/components/ui/label";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";

import {
  Users,
  Package,
  Wrench,
  Shield,
  Trash2,
  Edit,
  Search,
  Activity,
  Mail,
  Eye,
  User,
  ShoppingCart,
  TrendingUp,
  TrendingDown,
  Download,
  MoreVertical,
  X,
  BarChart3,
  DollarSign,
  Star,
  Plus,
  Zap,
  Save,
  RefreshCw,
  ImageIcon,
  Tag,
  Building2,
  Hash,
  FileText,
  AlertCircle,
  Settings,
  Clock,
  Bell,
  Lock,
  Copy,
  Check,
  Moon,
  Sun,
  Monitor,
  RotateCcw,
  Lock as LockIcon,
  Eye as EyeIcon,
  EyeOff,
  Loader,
  LogOut,
  ChevronDown,
} from "lucide-react";

import {
  adminService,
  buildService,
  componentService,
  userService,
} from "@/lib/database";
import {
  userActivityService,
  type UserActivity,
} from "@/lib/user-activity-service";
import { auditLogService, type AuditLogEntry } from "@/lib/audit-log-service";
import { formatCurrency } from "@/lib/currency";
import { supabase } from "@/lib/supabase";

/* ==================== TYPES ==================== */

interface User {
  user_id: number;
  user_name: string;
  email: string;
  user_type: "admin" | "user" | "moderator";
  created_at: string;
}

interface Build {
  build_id: number;
  build_name: string;
  user_id: number;
  total_price: number;
  date_created: string;
  users?: User;
  build_types?: { type_name: string };
}

interface Component {
  component_id: number;
  component_name: string;
  component_brand: string | null;
  component_price: number | null;
  component_description: string | null;
  component_image: string | null;
  component_categories?: { category_name: string };
  retailers?: { retailer_name: string };
}

interface Purchase {
  build_id: number;
  build_name: string;
  user_id: number;
  user_name?: string;
  user_email?: string;
  total_price: number;
  date_created: string;
  email_sent_to_retailer?: boolean;
  users?: User;
  build_types?: { type_name: string };
}

interface Stats {
  totalUsers: number;
  totalBuilds: number;
  totalComponents: number;
  totalPurchases: number;
  totalRevenue: number;
  activeUsers: number;
  recentActivity: number;
  avgBuildPrice: number;
  userGrowth: number;
  buildGrowth: number;
}

interface AdminSettings {
  theme: "light" | "dark" | "auto";
  itemsPerPage: number;
  autoRefreshInterval: number;
  defaultExportFormat: "json" | "csv";
  enableBulkActionConfirm: boolean;
  enableActivityLogging: boolean;
  notificationEmail: string;
  defaultPriceRange: string;
  showInactiveUsers: boolean;
  sessionTimeout: number;
  requireDeleteConfirm: boolean;
  dailyActivityReport: boolean;
  purchaseNotifications: boolean;
  userRegistrationAlerts: boolean;
}

/* ==================== FORM STATE TYPES ==================== */

interface NewUserForm {
  user_name: string;
  email: string;
  password: string;
  user_type: "admin" | "user" | "moderator";
}

interface NewComponentForm {
  component_name: string;
  component_brand: string;
  component_price: string;
  component_description: string;
  component_image: string;
  category_id: string;
  retailer_id: string;
}

interface EditComponentForm {
  component_name: string;
  component_brand: string;
  component_price: string;
  component_description: string;
  component_image: string;
}

/* ==================== DEFAULT SETTINGS ==================== */

const DEFAULT_SETTINGS: AdminSettings = {
  theme: "auto",
  itemsPerPage: 10,
  autoRefreshInterval: 300000,
  defaultExportFormat: "json",
  enableBulkActionConfirm: true,
  enableActivityLogging: true,
  notificationEmail: "",
  defaultPriceRange: "all",
  showInactiveUsers: false,
  sessionTimeout: 30,
  requireDeleteConfirm: true,
  dailyActivityReport: false,
  purchaseNotifications: true,
  userRegistrationAlerts: true,
};

/* ==================== MAIN COMPONENT ==================== */

export default function AdminPage() {
  const { user } = useAuth();
  const router = useRouter();

  // ==================== SETTINGS STATE ====================
  const [settings, setSettings] = useState<AdminSettings>(DEFAULT_SETTINGS);
  const [settingsSaved, setSettingsSaved] = useState(false);
  const [copiedField, setCopiedField] = useState<string | null>(null);

  // Settings dialogs
  const [changePasswordDialog, setChangePasswordDialog] = useState(false);
  const [passwordForm, setPasswordForm] = useState({
    current: "",
    new: "",
    confirm: "",
  });
  const [showPasswords, setShowPasswords] = useState({
    current: false,
    new: false,
    confirm: false,
  });
  const [clearLogsDialog, setClearLogsDialog] = useState(false);
  const [exportDialog, setExportDialog] = useState(false);

  // Auto-refresh state
  const [autoRefreshTimer, setAutoRefreshTimer] =
    useState<NodeJS.Timeout | null>(null);

  // Tab state
  const [activeTab, setActiveTab] = useState("overview");

  // Data state
  const [users, setUsers] = useState<User[]>([]);
  const [builds, setBuilds] = useState<Build[]>([]);
  const [components, setComponents] = useState<Component[]>([]);
  const [purchases, setPurchases] = useState<Purchase[]>([]);
  const [userActivity, setUserActivity] = useState<UserActivity[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [auditLogsLoading, setAuditLogsLoading] = useState(false);
  const [stats, setStats] = useState<Stats>({
    totalUsers: 0,
    totalBuilds: 0,
    totalComponents: 0,
    totalPurchases: 0,
    totalRevenue: 0,
    activeUsers: 0,
    recentActivity: 0,
    avgBuildPrice: 0,
    userGrowth: 0,
    buildGrowth: 0,
  });

  // UI state
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [imageUploading, setImageUploading] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  // Search & Filter
  const [searchTerm, setSearchTerm] = useState("");
  const [userTypeFilter, setUserTypeFilter] = useState<string>("all");
  const [activityTypeFilter, setActivityTypeFilter] = useState<string>("all");
  const [sortBy, setSortBy] = useState<string>("newest");
  const [priceRange, setPriceRange] = useState<string>("all");

  // Bulk actions
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [bulkAction, setBulkAction] = useState<string>("");

  // ==================== DIALOG STATES ====================

  const [deleteDialog, setDeleteDialog] = useState<{
    open: boolean;
    type: "user" | "build" | "component" | null;
    id: number | null;
    name: string;
  }>({ open: false, type: null, id: null, name: "" });

  const [createUserDialog, setCreateUserDialog] = useState(false);
  const [newUserForm, setNewUserForm] = useState<NewUserForm>({
    user_name: "",
    email: "",
    password: "",
    user_type: "user",
  });

  const [createComponentDialog, setCreateComponentDialog] = useState(false);
  const [newComponentForm, setNewComponentForm] = useState<NewComponentForm>({
    component_name: "",
    component_brand: "",
    component_price: "",
    component_description: "",
    component_image: "",
    category_id: "",
    retailer_id: "",
  });

  const [editImageDialog, setEditImageDialog] = useState<{
    open: boolean;
    component: Component | null;
    imageUrl: string;
  }>({ open: false, component: null, imageUrl: "" });

  const [editUserDialog, setEditUserDialog] = useState<{
    open: boolean;
    user: User | null;
    userType: string;
    userName: string;
    email: string;
  }>({ open: false, user: null, userType: "", userName: "", email: "" });

  const [editComponentDialog, setEditComponentDialog] = useState<{
    open: boolean;
    component: Component | null;
    form: EditComponentForm;
  }>({
    open: false,
    component: null,
    form: {
      component_name: "",
      component_brand: "",
      component_price: "",
      component_description: "",
      component_image: "",
    },
  });

  const [editBuildDialog, setEditBuildDialog] = useState<{
    open: boolean;
    build: Build | null;
    buildName: string;
  }>({ open: false, build: null, buildName: "" });

  // ==================== INITIALIZE SETTINGS ====================

  useEffect(() => {
    const savedSettings = localStorage.getItem("adminSettings");
    if (savedSettings) {
      try {
        setSettings(JSON.parse(savedSettings));
      } catch (e) {
        console.error("Failed to load settings:", e);
      }
    }
  }, []);

  // ==================== AUTO-REFRESH EFFECT ====================

  useEffect(() => {
    if (settings.autoRefreshInterval > 0 && activeTab !== "settings") {
      const timer = setInterval(() => {
        loadData();
      }, settings.autoRefreshInterval);
      setAutoRefreshTimer(timer);

      return () => {
        if (timer) clearInterval(timer);
      };
    }
  }, [settings.autoRefreshInterval, activeTab]);

  useEffect(() => {
    if (activeTab === "audit") {
      setAuditLogsLoading(true);
      auditLogService
        .getRecent(150)
        .then(setAuditLogs)
        .catch(() => setAuditLogs([]))
        .finally(() => setAuditLogsLoading(false));
    }
  }, [activeTab]);

  /* ==================== LOAD DATA ==================== */

  useEffect(() => {
    const passwordVerified =
      typeof window !== "undefined"
        ? sessionStorage.getItem("admin_password_verified")
        : null;

    if (user?.user_type === "admin") {
      loadData();
      return;
    }
    if (passwordVerified === "1") {
      loadData();
      return;
    }
    router.push("/admin-access");
  }, [user, router]);

  const showSuccess = (msg: string) => {
    setSuccessMessage(msg);
    setTimeout(() => setSuccessMessage(""), 3000);
    swal.success("Success", msg);
  };

  const showError = (msg: string) => {
    setErrorMessage(msg);
    setTimeout(() => setErrorMessage(""), 4000);
    swal.error("Error", msg);
  };

  const loadData = async () => {
    try {
      setLoading(true);
      const [
        usersData,
        buildsData,
        componentsData,
        purchasesData,
        activityResult,
      ] = await Promise.allSettled([
        adminService.getAllUsers(),
        adminService.getAllBuilds(),
        adminService.getAllComponents(),
        adminService.getAllPurchases(),
        userActivityService.getAllActivity(100),
      ]);

      const loadedUsers =
        usersData.status === "fulfilled" ? (usersData.value as User[]) : [];
      const loadedBuilds =
        buildsData.status === "fulfilled" ? (buildsData.value as Build[]) : [];
      const loadedComponents =
        componentsData.status === "fulfilled"
          ? (componentsData.value as Component[])
          : [];
      const loadedPurchases =
        purchasesData.status === "fulfilled"
          ? ((purchasesData.value || []) as Purchase[])
          : [];
      const loadedActivity =
        activityResult.status === "fulfilled" ? activityResult.value || [] : [];

      setUsers(loadedUsers);
      setBuilds(loadedBuilds);
      setComponents(loadedComponents);
      setPurchases(loadedPurchases);
      setUserActivity(loadedActivity);
      calculateStats(
        loadedUsers,
        loadedBuilds,
        loadedComponents,
        loadedPurchases,
        loadedActivity,
      );
    } catch (error) {
      console.error("Error loading admin data:", error);
      showError("Failed to load data. Please refresh.");
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (
    u: User[],
    b: Build[],
    c: Component[],
    p: Purchase[],
    a: UserActivity[],
  ) => {
    const totalRevenue = b.reduce(
      (sum, build) => sum + (build.total_price || 0),
      0,
    );
    const avgBuildPrice = b.length > 0 ? totalRevenue / b.length : 0;
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    const recentActivity = a.filter(
      (activity) => new Date(activity.created_at) > sevenDaysAgo,
    ).length;
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const recentLogins = a.filter(
      (activity) =>
        activity.activity_type === "login" &&
        new Date(activity.created_at) > thirtyDaysAgo,
    );
    const activeUsers = new Set(recentLogins.map((a) => a.user_id)).size;
    setStats({
      totalUsers: u.length,
      totalBuilds: b.length,
      totalComponents: c.length,
      totalPurchases: p.length,
      totalRevenue,
      activeUsers,
      recentActivity,
      avgBuildPrice,
      userGrowth: 12.5,
      buildGrowth: 8.3,
    });
  };

  /* ==================== SETTINGS HANDLERS ==================== */

  const handleSaveSettings = () => {
    try {
      localStorage.setItem("adminSettings", JSON.stringify(settings));
      setSettingsSaved(true);
      showSuccess("Settings saved successfully!");
      setTimeout(() => setSettingsSaved(false), 3000);
    } catch (error) {
      console.error("Error saving settings:", error);
      showError("Failed to save settings.");
    }
  };

  const handleResetSettings = () => {
    setSettings(DEFAULT_SETTINGS);
    localStorage.removeItem("adminSettings");
    showSuccess("Settings reset to defaults!");
  };

  const handleCopyField = (text: string, field: string) => {
    navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 2000);
  };

  const uploadComponentImage = async (
    file: File
  ): Promise<string | null> => {
    if (!file.type.startsWith("image/")) {
      showError("Please select an image file (e.g. JPG, PNG).");
      return null;
    }
    setImageUploading(true);
    try {
      const ext = file.name.split(".").pop() || "jpg";
      const name = `${Date.now()}-${Math.random().toString(36).slice(2, 9)}.${ext}`;
      const { data, error } = await supabase.storage
        .from("component-images")
        .upload(name, file, {
          cacheControl: "3600",
          upsert: false,
        });
      if (error) {
        showError(error.message || "Upload failed.");
        return null;
      }
      const {
        data: { publicUrl },
      } = supabase.storage.from("component-images").getPublicUrl(data.path);
      return publicUrl;
    } catch (e) {
      showError("Upload failed. Please try again.");
      return null;
    } finally {
      setImageUploading(false);
    }
  };

  // ==================== LOGOUT HANDLER ====================

  const handleLogout = async () => {
    try {
      setActionLoading(true);
      // Clear session storage
      sessionStorage.removeItem("admin_password_verified");
      // Call logout from auth context if available
      // await authService.logout();
      showSuccess("Logged out successfully!");
      // Redirect to login page
      setTimeout(() => {
        router.push("/admin-access");
      }, 1000);
    } catch (error) {
      console.error("Error logging out:", error);
      showError("Failed to logout. Please try again.");
    } finally {
      setActionLoading(false);
    }
  };

  // ==================== THEME HANDLER ====================

  const handleThemeChange = (newTheme: "light" | "dark" | "auto") => {
    setSettings({ ...settings, theme: newTheme });

    // Apply theme immediately
    if (newTheme === "dark") {
      document.documentElement.classList.add("dark");
    } else if (newTheme === "light") {
      document.documentElement.classList.remove("dark");
    } else if (newTheme === "auto") {
      const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
      if (isDark) {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    }
  };

  // ==================== PASSWORD HANDLER ====================

  const handleChangePassword = async () => {
    if (
      !passwordForm.current.trim() ||
      !passwordForm.new.trim() ||
      !passwordForm.confirm.trim()
    ) {
      showError("All password fields are required.");
      return;
    }

    if (passwordForm.new !== passwordForm.confirm) {
      showError("New passwords do not match.");
      return;
    }

    if (passwordForm.new.length < 8) {
      showError("New password must be at least 8 characters.");
      return;
    }

    try {
      setActionLoading(true);
      // Call your auth service to change password
      // await authService.changePassword(passwordForm.current, passwordForm.new)

      setChangePasswordDialog(false);
      setPasswordForm({ current: "", new: "", confirm: "" });
      showSuccess("Password changed successfully!");
    } catch (error) {
      console.error("Error changing password:", error);
      showError("Failed to change password. Check your current password.");
    } finally {
      setActionLoading(false);
    }
  };

  // ==================== EMAIL NOTIFICATION HANDLER ====================

  const handleSendTestEmail = async () => {
    if (!settings.notificationEmail) {
      showError("Please enter a notification email address first.");
      return;
    }

    try {
      setActionLoading(true);
      // Call your email service
      // await emailService.sendTestEmail(settings.notificationEmail)

      showSuccess(`Test email sent to ${settings.notificationEmail}`);
    } catch (error) {
      console.error("Error sending test email:", error);
      showError("Failed to send test email. Please check the email address.");
    } finally {
      setActionLoading(false);
    }
  };

  // ==================== EXPORT HANDLERS ====================

  const handleExportAllData = async () => {
    try {
      setActionLoading(true);

      const allData = {
        users,
        builds,
        components,
        purchases,
        activity: userActivity,
        stats,
        exportedAt: new Date().toISOString(),
        exportedBy: user?.user_name || "Admin",
      };

      const format = settings.defaultExportFormat;
      let content: string;
      let filename: string;
      let mimeType: string;

      if (format === "csv") {
        // Convert to CSV
        content = convertToCSV(allData);
        filename = `admin-backup-${new Date().toISOString().split("T")[0]}.csv`;
        mimeType = "text/csv";
      } else {
        // JSON format
        content = JSON.stringify(allData, null, 2);
        filename = `admin-backup-${new Date().toISOString().split("T")[0]}.json`;
        mimeType = "application/json";
      }

      const blob = new Blob([content], { type: mimeType });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = filename;
      link.click();
      URL.revokeObjectURL(url);

      showSuccess(`Data exported successfully as ${filename}`);
    } catch (error) {
      console.error("Error exporting data:", error);
      showError("Failed to export data.");
    } finally {
      setActionLoading(false);
    }
  };

  // ==================== CLEAR LOGS HANDLER ====================

  const handleClearActivityLogs = async () => {
    try {
      setActionLoading(true);
      // Call your activity service to clear logs
      // await userActivityService.clearAllLogs()

      setUserActivity([]);
      setClearLogsDialog(false);
      showSuccess("Activity logs cleared successfully!");
      loadData();
    } catch (error) {
      console.error("Error clearing logs:", error);
      showError("Failed to clear activity logs.");
    } finally {
      setActionLoading(false);
    }
  };

  // ==================== BACKUP & RESTORE ====================

  const handleBackupSettings = () => {
    try {
      const backup = {
        settings,
        backupDate: new Date().toISOString(),
        backupVersion: "1.0",
      };

      const blob = new Blob([JSON.stringify(backup, null, 2)], {
        type: "application/json",
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `settings-backup-${new Date().toISOString().split("T")[0]}.json`;
      link.click();
      URL.revokeObjectURL(url);

      showSuccess("Settings backed up successfully!");
    } catch (error) {
      console.error("Error backing up settings:", error);
      showError("Failed to backup settings.");
    }
  };

  const handleRestoreSettings = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".json";
    input.onchange = async (e: any) => {
      try {
        const file = e.target.files[0];
        const text = await file.text();
        const backup = JSON.parse(text);

        if (backup.settings && backup.backupVersion) {
          setSettings(backup.settings);
          localStorage.setItem(
            "adminSettings",
            JSON.stringify(backup.settings),
          );
          showSuccess("Settings restored successfully!");
        } else {
          showError("Invalid backup file format.");
        }
      } catch (error) {
        console.error("Error restoring settings:", error);
        showError("Failed to restore settings. Invalid file.");
      }
    };
    input.click();
  };

  // ==================== CSV CONVERSION ====================

  const convertToCSV = (data: any): string => {
    const headers = ["Type", "Item", "Value", "Date"];
    let csv = headers.join(",") + "\n";

    // Add users
    data.users.forEach((u: User) => {
      csv += `User,"${u.user_name}","${u.email}","${u.created_at}"\n`;
    });

    // Add builds
    data.builds.forEach((b: Build) => {
      csv += `Build,"${b.build_name}","${formatCurrency(b.total_price)}","${b.date_created}"\n`;
    });

    // Add components
    data.components.forEach((c: Component) => {
      csv += `Component,"${c.component_name}","${formatCurrency(c.component_price || 0)}","${c.component_brand || "N/A"}"\n`;
    });

    return csv;
  };

  /* ==================== CREATE HANDLERS ==================== */

  const handleCreateUser = async () => {
    if (
      !newUserForm.user_name.trim() ||
      !newUserForm.email.trim() ||
      !newUserForm.password.trim()
    ) {
      showError("Please fill in all required fields.");
      return;
    }
    try {
      setActionLoading(true);
      await userService.create({
        user_name: newUserForm.user_name,
        email: newUserForm.email,
        password: newUserForm.password,
        user_type: newUserForm.user_type,
      });
      setCreateUserDialog(false);
      setNewUserForm({
        user_name: "",
        email: "",
        password: "",
        user_type: "user",
      });
      showSuccess(`User "${newUserForm.user_name}" created successfully!`);
      loadData();
    } catch (error) {
      console.error("Error creating user:", error);
      showError("Failed to create user. Email may already be in use.");
    } finally {
      setActionLoading(false);
    }
  };

  const handleCreateComponent = async () => {
    if (!newComponentForm.component_name.trim()) {
      showError("Component name is required.");
      return;
    }
    try {
      setActionLoading(true);

      const categoryId = newComponentForm.category_id
        ? parseInt(newComponentForm.category_id)
        : null;
      const retailerId = newComponentForm.retailer_id
        ? parseInt(newComponentForm.retailer_id)
        : null;

      await componentService.create({
        component_name: newComponentForm.component_name,
        component_brand: newComponentForm.component_brand || null,
        component_price: newComponentForm.component_price
          ? parseFloat(newComponentForm.component_price)
          : null,
        component_description: newComponentForm.component_description || null,
        component_image: newComponentForm.component_image || null,
        category_id: categoryId as number,
        retailer_id: retailerId as number,
      });

      setCreateComponentDialog(false);
      setNewComponentForm({
        component_name: "",
        component_brand: "",
        component_price: "",
        component_description: "",
        component_image: "",
        category_id: "",
        retailer_id: "",
      });
      showSuccess(
        `Component "${newComponentForm.component_name}" created successfully!`,
      );
      loadData();
    } catch (error) {
      console.error("Error creating component:", error);
      showError("Failed to create component. Please try again.");
    } finally {
      setActionLoading(false);
    }
  };

  /* ==================== UPDATE HANDLERS ==================== */

  const handleUpdateUser = async () => {
    if (!editUserDialog.user) return;
    if (!editUserDialog.userName.trim() || !editUserDialog.email.trim()) {
      showError("Name and email are required.");
      return;
    }
    try {
      setActionLoading(true);
      await userService.update(editUserDialog.user.user_id, {
        user_name: editUserDialog.userName,
        email: editUserDialog.email,
        user_type: editUserDialog.userType as "admin" | "user" | "moderator",
      });
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "user_updated",
          targetType: "user",
          targetId: editUserDialog.user.user_id,
          targetName: editUserDialog.userName,
        });
      setEditUserDialog({
        open: false,
        user: null,
        userType: "",
        userName: "",
        email: "",
      });
      showSuccess("User updated successfully!");
      loadData();
    } catch (error) {
      console.error("Error updating user:", error);
      showError("Failed to update user.");
    } finally {
      setActionLoading(false);
    }
  };

  const handleUpdateComponent = async () => {
    if (!editComponentDialog.component) return;
    if (!editComponentDialog.form.component_name.trim()) {
      showError("Component name is required.");
      return;
    }
    try {
      setActionLoading(true);
      await componentService.update(
        editComponentDialog.component.component_id,
        {
          component_name: editComponentDialog.form.component_name,
          component_brand: editComponentDialog.form.component_brand || null,
          component_price: editComponentDialog.form.component_price
            ? parseFloat(editComponentDialog.form.component_price)
            : null,
          component_description:
            editComponentDialog.form.component_description || null,
          component_image: editComponentDialog.form.component_image || null,
        },
      );
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "component_updated",
          targetType: "component",
          targetId: editComponentDialog.component.component_id,
          targetName: editComponentDialog.form.component_name,
        });
      setEditComponentDialog({
        open: false,
        component: null,
        form: {
          component_name: "",
          component_brand: "",
          component_price: "",
          component_description: "",
          component_image: "",
        },
      });
      showSuccess("Component updated successfully!");
      loadData();
    } catch (error) {
      console.error("Error updating component:", error);
      showError("Failed to update component.");
    } finally {
      setActionLoading(false);
    }
  };

  const handleUpdateBuildName = async () => {
    if (!editBuildDialog.build) return;
    if (!editBuildDialog.buildName.trim()) {
      showError("Build name is required.");
      return;
    }
    try {
      setActionLoading(true);
      await buildService.update(editBuildDialog.build.build_id, {
        build_name: editBuildDialog.buildName,
        total_price: editBuildDialog.build.total_price,
      });
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "build_updated",
          targetType: "build",
          targetId: editBuildDialog.build.build_id,
          targetName: editBuildDialog.buildName,
        });
      setEditBuildDialog({ open: false, build: null, buildName: "" });
      showSuccess("Build name updated successfully!");
      loadData();
    } catch (error) {
      console.error("Error updating build:", error);
      showError("Failed to update build.");
    } finally {
      setActionLoading(false);
    }
  };

  const handleUpdateImage = async () => {
    if (!editImageDialog.component) return;
    try {
      setActionLoading(true);
      await componentService.update(editImageDialog.component.component_id, {
        component_image: editImageDialog.imageUrl || null,
      });
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "component_image_updated",
          targetType: "component",
          targetId: editImageDialog.component.component_id,
          targetName: editImageDialog.component.component_name,
        });
      setEditImageDialog({ open: false, component: null, imageUrl: "" });
      showSuccess("Component image updated!");
      loadData();
    } catch (error) {
      console.error("Error updating component image:", error);
      showError("Failed to update component image.");
    } finally {
      setActionLoading(false);
    }
  };

  /* ==================== DELETE HANDLERS ==================== */

  const handleDeleteUser = async () => {
    if (!deleteDialog.id) return;
    try {
      await adminService.deleteUser(deleteDialog.id);
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "user_deleted",
          targetType: "user",
          targetId: deleteDialog.id,
          targetName: deleteDialog.name,
        });
      setDeleteDialog({ open: false, type: null, id: null, name: "" });
      showSuccess("User deleted successfully.");
      loadData();
    } catch (error) {
      console.error("Error deleting user:", error);
      showError("Failed to delete user.");
    }
  };

  const handleDeleteBuild = async () => {
    if (!deleteDialog.id) return;
    try {
      await adminService.deleteBuild(deleteDialog.id);
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "build_deleted",
          targetType: "build",
          targetId: deleteDialog.id,
          targetName: deleteDialog.name,
        });
      setDeleteDialog({ open: false, type: null, id: null, name: "" });
      showSuccess("Build deleted successfully.");
      loadData();
    } catch (error) {
      console.error("Error deleting build:", error);
      showError("Failed to delete build.");
    }
  };

  const handleDeleteComponent = async () => {
    if (!deleteDialog.id) return;
    try {
      await adminService.deleteComponent(deleteDialog.id);
      if (user)
        auditLogService.log({
          adminUserId: user.user_id,
          action: "component_deleted",
          targetType: "component",
          targetId: deleteDialog.id,
          targetName: deleteDialog.name,
        });
      setDeleteDialog({ open: false, type: null, id: null, name: "" });
      showSuccess("Component deleted successfully.");
      loadData();
    } catch (error) {
      console.error("Error deleting component:", error);
      showError("Failed to delete component.");
    }
  };

  /* ==================== BULK ACTIONS ==================== */

  const handleBulkAction = async () => {
    if (!bulkAction || selectedItems.length === 0) return;
    try {
      if (bulkAction === "delete") {
        for (const id of selectedItems) {
          if (activeTab === "users") await adminService.deleteUser(id);
          if (activeTab === "builds") await adminService.deleteBuild(id);
          if (activeTab === "components")
            await adminService.deleteComponent(id);
        }
        if (user) {
          const action =
            activeTab === "users"
              ? "bulk_delete_users"
              : activeTab === "builds"
                ? "bulk_delete_builds"
                : "bulk_delete_components";
          auditLogService.log({
            adminUserId: user.user_id,
            action,
            targetType: activeTab === "users" ? "user" : activeTab === "builds" ? "build" : "component",
            targetName: `${selectedItems.length} items`,
            details: { count: selectedItems.length, ids: selectedItems },
          });
        }
        showSuccess(`${selectedItems.length} items deleted successfully.`);
      }
      setSelectedItems([]);
      setBulkAction("");
      loadData();
    } catch (error) {
      console.error("Error performing bulk action:", error);
      showError("Bulk action failed on some items.");
    }
  };

  const toggleSelectItem = (id: number) => {
    setSelectedItems((prev) =>
      prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id],
    );
  };

  const toggleSelectAll = () => {
    if (activeTab === "users")
      setSelectedItems(
        selectedItems.length === filteredUsers.length
          ? []
          : filteredUsers.map((u) => u.user_id),
      );
    else if (activeTab === "builds")
      setSelectedItems(
        selectedItems.length === filteredBuilds.length
          ? []
          : filteredBuilds.map((b) => b.build_id),
      );
    else if (activeTab === "components")
      setSelectedItems(
        selectedItems.length === filteredComponents.length
          ? []
          : filteredComponents.map((c) => c.component_id),
      );
  };

  /* ==================== EXPORT ==================== */

  const handleExport = (type: string) => {
    const dataMap: Record<string, { data: any[]; filename: string }> = {
      users: { data: users, filename: "users-export.json" },
      builds: { data: builds, filename: "builds-export.json" },
      components: { data: components, filename: "components-export.json" },
    };
    const { data, filename } = dataMap[type] || {
      data: [],
      filename: "export.json",
    };
    const blob = new Blob([JSON.stringify(data, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  };

  /* ==================== FILTERING ==================== */

  const filteredUsers = users
    .filter(
      (u) =>
        (u.user_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          u.email.toLowerCase().includes(searchTerm.toLowerCase())) &&
        (userTypeFilter === "all" || u.user_type === userTypeFilter),
    )
    .sort((a, b) => {
      if (sortBy === "newest")
        return (
          new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
        );
      if (sortBy === "oldest")
        return (
          new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
        );
      if (sortBy === "name") return a.user_name.localeCompare(b.user_name);
      return 0;
    });

  const filteredBuilds = builds
    .filter(
      (b) =>
        b.build_name.toLowerCase().includes(searchTerm.toLowerCase()) &&
        (priceRange === "all" ||
          (priceRange === "low" && b.total_price < 30000) ||
          (priceRange === "medium" &&
            b.total_price >= 30000 &&
            b.total_price < 80000) ||
          (priceRange === "high" && b.total_price >= 80000)),
    )
    .sort((a, b) => {
      if (sortBy === "newest")
        return (
          new Date(b.date_created).getTime() -
          new Date(a.date_created).getTime()
        );
      if (sortBy === "oldest")
        return (
          new Date(a.date_created).getTime() -
          new Date(b.date_created).getTime()
        );
      if (sortBy === "price-high") return b.total_price - a.total_price;
      if (sortBy === "price-low") return a.total_price - b.total_price;
      return 0;
    });

  const filteredComponents = components.filter(
    (c) =>
      c.component_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (c.component_brand &&
        c.component_brand.toLowerCase().includes(searchTerm.toLowerCase())),
  );

  const filteredActivity = userActivity.filter(
    (a) =>
      activityTypeFilter === "all" || a.activity_type === activityTypeFilter,
  );

  /* ==================== RENDER ==================== */

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800">
        <div className="text-center">
          <Activity className="h-12 w-12 animate-spin mx-auto mb-4 text-amber-600" />
          <p className="text-muted-foreground">Loading admin dashboard...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="admin-page min-h-screen bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800 p-4 sm:p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* ==================== TOAST NOTIFICATIONS ==================== */}
        {successMessage && (
          <div className="fixed top-4 right-4 z-50 bg-green-600 text-white px-5 py-3 rounded-xl shadow-xl flex items-center gap-3 animate-in slide-in-from-top-2">
            <div className="w-2 h-2 rounded-full bg-green-300" />
            {successMessage}
          </div>
        )}
        {errorMessage && (
          <div className="fixed top-4 right-4 z-50 bg-red-600 text-white px-5 py-3 rounded-xl shadow-xl flex items-center gap-3 animate-in slide-in-from-top-2">
            <AlertCircle className="h-4 w-4" />
            {errorMessage}
          </div>
        )}

        {/* ==================== HEADER ==================== */}
        <div className="rounded-xl sm:rounded-2xl border border-slate-200/80 dark:border-slate-700/80 bg-white/90 dark:bg-slate-900/90 shadow-sm backdrop-blur-sm p-4 sm:p-6">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex items-start gap-4">
              <div className="rounded-xl bg-amber-500/10 dark:bg-amber-500/20 p-3 border border-amber-500/20">
                <Shield className="h-8 w-8 text-amber-600 dark:text-amber-400" />
              </div>
              <div>
                <h1 className="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white">
                  BuildMate
                </h1>
                <p className="text-slate-600 dark:text-slate-400 mt-1 text-sm sm:text-base">
                  ADMINSTRATOR
                </p>
                {user && (
                  <div className="mt-2 flex items-center gap-2 text-xs text-slate-500 dark:text-slate-400">
                    <span>Signed in as</span>
                    <Badge variant="secondary" className="font-normal">
                      {user.user_name || user.email}
                    </Badge>
                  </div>
                )}
              </div>
            </div>
            <div className="flex items-center gap-2 flex-wrap">
              <Link href="/admin/businesses">
                <Button variant="outline" size="default" className="min-h-11 px-4 hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 transition-transform">
                  <Building2 className="h-4 w-4 mr-2" />
                  Businesses
                </Button>
              </Link>
              <Link href="/admin/authorizations">
                <Button variant="outline" size="default" className="min-h-11 px-4 hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 transition-transform">
                  <Shield className="h-4 w-4 mr-2" />
                  Authorizations
                </Button>
              </Link>
              <Button variant="outline" size="default" onClick={loadData} className="min-h-11 px-4 hover:-translate-y-0.5 hover:shadow-md active:translate-y-0 transition-transform">
                <RefreshCw className="h-4 w-4 mr-2" />
                Refresh
              </Button>
            </div>
          </div>
        </div>

        {/* ==================== TABS ==================== */}
        <Tabs
          value={activeTab}
          onValueChange={(val) => {
            setActiveTab(val);
            setSelectedItems([]);
          }}
        >
          <TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 lg:grid-cols-7 h-auto gap-3 p-3 bg-slate-100 dark:bg-slate-800/80 rounded-xl transition-colors">
            <TabsTrigger value="overview" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <BarChart3 className="h-4 w-4 mr-2 shrink-0" />
              Overview
            </TabsTrigger>
            <TabsTrigger value="users" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <Users className="h-4 w-4 mr-2 shrink-0" />
              Users
            </TabsTrigger>
            <TabsTrigger value="builds" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <Wrench className="h-4 w-4 mr-2 shrink-0" />
              Builds
            </TabsTrigger>
            <TabsTrigger value="components" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <Package className="h-4 w-4 mr-2 shrink-0" />
              Components
            </TabsTrigger>
            <TabsTrigger value="purchases" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <ShoppingCart className="h-4 w-4 mr-2 shrink-0" />
              Purchases
            </TabsTrigger>
            <TabsTrigger value="activity" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <Activity className="h-4 w-4 mr-2 shrink-0" />
              Activity
            </TabsTrigger>
            <TabsTrigger value="audit" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <FileText className="h-4 w-4 mr-2 shrink-0" />
              Audit
            </TabsTrigger>
            <TabsTrigger value="settings" className="rounded-lg min-h-12 px-5 py-3 transition-all data-[state=active]:bg-white dark:data-[state=active]:bg-slate-700 data-[state=active]:shadow-sm touch-manipulation hover:bg-white/80 hover:shadow-md dark:hover:bg-slate-600/60 cursor-pointer">
              <Settings className="h-4 w-4 mr-2 shrink-0" />
              Settings
            </TabsTrigger>
          </TabsList>

          {/* ==================== OVERVIEW TAB ==================== */}
          <TabsContent value="overview" className="space-y-4 overflow-x-hidden">
            <div className="grid gap-3 sm:gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
              <StatCard
                icon={<Users className="h-5 w-5" />}
                label="Total Users"
                value={stats.totalUsers}
                subtext={`${stats.activeUsers} active`}
                trend={stats.userGrowth}
                color="blue"
              />
              <StatCard
                icon={<Wrench className="h-5 w-5" />}
                label="Total Builds"
                value={stats.totalBuilds}
                subtext={`Avg ${formatCurrency(stats.avgBuildPrice)}`}
                trend={stats.buildGrowth}
                color="green"
              />
              <StatCard
                icon={<Package className="h-5 w-5" />}
                label="Components"
                value={stats.totalComponents}
                subtext="In database"
                color="purple"
              />
              <StatCard
                icon={<DollarSign className="h-5 w-5" />}
                label="Total Revenue"
                value={formatCurrency(stats.totalRevenue)}
                subtext={`${stats.totalPurchases} purchases`}
                color="amber"
              />
            </div>

            <div className="grid gap-3 sm:gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
              <Card className="overflow-hidden">
                <CardHeader className="p-4 sm:p-6 pb-2">
                  <CardTitle className="text-sm font-medium">
                    User Distribution
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-2 p-4 sm:p-6 pt-0">
                  <div className="flex justify-between text-sm">
                    <span>Admins</span>
                    <Badge>
                      {users.filter((u) => u.user_type === "admin").length}
                    </Badge>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>Moderators</span>
                    <Badge variant="secondary">
                      {users.filter((u) => u.user_type === "moderator").length}
                    </Badge>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>Regular Users</span>
                    <Badge variant="outline">
                      {users.filter((u) => u.user_type === "user").length}
                    </Badge>
                  </div>
                </CardContent>
              </Card>
              <Card className="overflow-hidden">
                <CardHeader className="p-4 sm:p-6 pb-2">
                  <CardTitle className="text-sm font-medium">
                    Recent Activity
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-4 sm:p-6 pt-0">
                  <div className="text-3xl font-bold">
                    {stats.recentActivity}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Actions in the last 7 days
                  </p>
                  <div className="mt-3 space-y-1">
                    {userActivity.slice(0, 3).map((activity) => (
                      <div
                        key={activity.activity_id}
                        className="text-xs text-muted-foreground truncate"
                      >
                        • {activity.activity_type}
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
              <Card className="overflow-hidden">
                <CardHeader className="p-4 sm:p-6 pb-2">
                  <CardTitle className="text-sm font-medium">
                    Top Builds by Price
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-2 p-4 sm:p-6 pt-0">
                  {builds
                    .sort((a, b) => b.total_price - a.total_price)
                    .slice(0, 3)
                    .map((build) => (
                      <div
                        key={build.build_id}
                        className="flex justify-between text-sm"
                      >
                        <span className="truncate flex-1">
                          {build.build_name}
                        </span>
                        <span className="font-semibold ml-2">
                          {formatCurrency(build.total_price)}
                        </span>
                      </div>
                    ))}
                </CardContent>
              </Card>
            </div>

            <div className="grid gap-3 sm:gap-4 grid-cols-1 lg:grid-cols-2">
              <Card className="overflow-hidden">
                <CardHeader className="p-4 sm:p-6 pb-2">
                  <CardTitle className="text-base sm:text-lg">Recent Builds</CardTitle>
                  <CardDescription className="text-sm">Latest PC builds created</CardDescription>
                </CardHeader>
                <CardContent className="space-y-2 p-4 sm:p-6 pt-0">
                  {builds.slice(0, 5).map((build) => (
                    <div
                      key={build.build_id}
                      className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2 p-3 border rounded-lg min-w-0"
                    >
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-sm truncate">
                          {build.build_name}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          by {build.users?.user_name || "Unknown"}
                        </p>
                      </div>
                      <div className="flex items-center justify-between sm:justify-end gap-2 shrink-0">
                        <p className="font-semibold text-sm">
                          {formatCurrency(build.total_price)}
                        </p>
                        <Button variant="ghost" size="sm" asChild className="shrink-0">
                          <Link href={`/builds/${build.build_id}?fromAdmin=1`}>
                            <Eye className="h-3 w-3" />
                          </Link>
                        </Button>
                      </div>
                    </div>
                  ))}
                </CardContent>
              </Card>
              <Card className="overflow-hidden">
                <CardHeader className="p-4 sm:p-6 pb-2">
                  <CardTitle className="text-base sm:text-lg">Component Categories</CardTitle>
                  <CardDescription className="text-sm">Distribution by category</CardDescription>
                </CardHeader>
                <CardContent className="space-y-2 p-4 sm:p-6 pt-0">
                  {Array.from(
                    new Set(
                      components
                        .map((c) => c.component_categories?.category_name)
                        .filter(Boolean),
                    ),
                  )
                    .slice(0, 5)
                    .map((category) => {
                      const count = components.filter(
                        (c) =>
                          c.component_categories?.category_name === category,
                      ).length;
                      return (
                        <div
                          key={category}
                          className="flex justify-between items-center"
                        >
                          <span className="text-sm">{category}</span>
                          <Badge>{count}</Badge>
                        </div>
                      );
                    })}
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* ==================== USERS TAB ==================== */}
          <TabsContent value="users" className="space-y-4">
            <div className="flex flex-wrap gap-2 items-center justify-between">
              <div className="flex gap-2 flex-1 flex-wrap">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="Search users..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-8"
                  />
                </div>
                <Select
                  value={userTypeFilter}
                  onValueChange={setUserTypeFilter}
                >
                  <SelectTrigger className="w-40">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Types</SelectItem>
                    <SelectItem value="admin">Admin</SelectItem>
                    <SelectItem value="moderator">Moderator</SelectItem>
                    <SelectItem value="user">User</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger className="w-40">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="newest">Newest First</SelectItem>
                    <SelectItem value="oldest">Oldest First</SelectItem>
                    <SelectItem value="name">By Name</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex gap-2">
                {selectedItems.length > 0 && (
                  <>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setSelectedItems([])}
                    >
                      <X className="h-4 w-4 mr-2" />
                      Clear ({selectedItems.length})
                    </Button>
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => setBulkAction("delete")}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      Delete Selected
                    </Button>
                  </>
                )}
                <Button
                  size="sm"
                  onClick={() => setCreateUserDialog(true)}
                  className="bg-amber-600 hover:bg-amber-700 text-white"
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Add User
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleExport("users")}
                >
                  <Download className="h-4 w-4 mr-2" />
                  Export
                </Button>
              </div>
            </div>

            <Card>
              <CardHeader>
                <div className="flex justify-between items-center">
                  <div>
                    <CardTitle>User Management</CardTitle>
                    <CardDescription>
                      {filteredUsers.length} users found
                    </CardDescription>
                  </div>
                  <Button variant="ghost" size="sm" onClick={toggleSelectAll}>
                    {selectedItems.length === filteredUsers.length
                      ? "Deselect All"
                      : "Select All"}
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {filteredUsers.map((u) => (
                    <div
                      key={u.user_id}
                      className="flex items-center gap-4 p-4 border rounded-lg hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors"
                    >
                      <Checkbox
                        checked={selectedItems.includes(u.user_id)}
                        onCheckedChange={() => toggleSelectItem(u.user_id)}
                      />
                      <div className="h-10 w-10 rounded-full bg-gradient-to-br from-blue-400 to-blue-600 flex items-center justify-center text-white font-bold flex-shrink-0">
                        {u.email.charAt(0).toUpperCase()}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-medium truncate">
                          {u.user_name}
                        </div>
                        <div className="text-sm text-muted-foreground truncate">
                          {u.email}
                        </div>
                        <div className="flex gap-2 mt-1">
                          <Badge
                            variant={
                              u.user_type === "admin"
                                ? "default"
                                : u.user_type === "moderator"
                                  ? "secondary"
                                  : "outline"
                            }
                          >
                            {u.user_type}
                          </Badge>
                          <span className="text-xs text-muted-foreground">
                            Joined {new Date(u.created_at).toLocaleDateString()}
                          </span>
                        </div>
                      </div>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>Actions</DropdownMenuLabel>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() =>
                              setEditUserDialog({
                                open: true,
                                user: u,
                                userType: u.user_type,
                                userName: u.user_name,
                                email: u.email,
                              })
                            }
                          >
                            <Edit className="h-4 w-4 mr-2" />
                            Edit User
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() =>
                              setDeleteDialog({
                                open: true,
                                type: "user",
                                id: u.user_id,
                                name: u.user_name,
                              })
                            }
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Delete User
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  ))}
                  {filteredUsers.length === 0 && (
                    <div className="text-center py-10 text-muted-foreground">
                      No users found
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* ==================== BUILDS TAB ==================== */}
          <TabsContent value="builds" className="space-y-4">
            <div className="flex flex-wrap gap-2 items-center justify-between">
              <div className="flex gap-2 flex-1 flex-wrap">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="Search builds..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-8"
                  />
                </div>
                <Select value={priceRange} onValueChange={setPriceRange}>
                  <SelectTrigger className="w-40">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Prices</SelectItem>
                    <SelectItem value="low">&lt; ₱30,000</SelectItem>
                    <SelectItem value="medium">₱30k - ₱80k</SelectItem>
                    <SelectItem value="high">&gt; ₱80,000</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger className="w-40">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="newest">Newest First</SelectItem>
                    <SelectItem value="oldest">Oldest First</SelectItem>
                    <SelectItem value="price-high">
                      Price: High to Low
                    </SelectItem>
                    <SelectItem value="price-low">
                      Price: Low to High
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex gap-2">
                {selectedItems.length > 0 && (
                  <>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setSelectedItems([])}
                    >
                      <X className="h-4 w-4 mr-2" />
                      Clear ({selectedItems.length})
                    </Button>
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => setBulkAction("delete")}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      Delete Selected
                    </Button>
                  </>
                )}
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleExport("builds")}
                >
                  <Download className="h-4 w-4 mr-2" />
                  Export
                </Button>
              </div>
            </div>

            <Card>
              <CardHeader>
                <div className="flex justify-between items-center">
                  <div>
                    <CardTitle>Build Management</CardTitle>
                    <CardDescription>
                      {filteredBuilds.length} builds found
                    </CardDescription>
                  </div>
                  <Button variant="ghost" size="sm" onClick={toggleSelectAll}>
                    {selectedItems.length === filteredBuilds.length
                      ? "Deselect All"
                      : "Select All"}
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {filteredBuilds.map((build) => (
                    <div
                      key={build.build_id}
                      className="flex items-center gap-4 p-4 border rounded-lg hover:bg-slate-50 dark:hover:bg-slate-800/50"
                    >
                      <Checkbox
                        checked={selectedItems.includes(build.build_id)}
                        onCheckedChange={() => toggleSelectItem(build.build_id)}
                      />
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-lg truncate">
                          {build.build_name}
                        </div>
                        <div className="text-sm text-muted-foreground">
                          By: {build.users?.user_name || "Unknown"} •{" "}
                          {new Date(build.date_created).toLocaleDateString()}
                        </div>
                        {build.build_types && (
                          <Badge variant="outline" className="mt-1">
                            {build.build_types.type_name}
                          </Badge>
                        )}
                      </div>
                      <div className="text-right">
                        <div className="font-bold text-xl text-amber-600">
                          {formatCurrency(build.total_price)}
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button variant="outline" size="sm" asChild>
                          <Link href={`/builds/${build.build_id}?fromAdmin=1`}>
                            <Eye className="h-4 w-4 mr-2" />
                            View
                          </Link>
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() =>
                            setEditBuildDialog({
                              open: true,
                              build,
                              buildName: build.build_name,
                            })
                          }
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() =>
                            setDeleteDialog({
                              open: true,
                              type: "build",
                              id: build.build_id,
                              name: build.build_name,
                            })
                          }
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {filteredBuilds.length === 0 && (
                    <div className="text-center py-10 text-muted-foreground">
                      No builds found
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* ==================== COMPONENTS TAB ==================== */}
          <TabsContent value="components" className="space-y-6">
            <div className="flex flex-wrap gap-2 items-center justify-between bg-white/50 dark:bg-slate-900/50 p-4 rounded-xl border border-slate-200 dark:border-slate-800 backdrop-blur-sm">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search inventory..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 bg-white dark:bg-slate-950"
                />
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handleExport("components")}
              >
                <Download className="h-4 w-4 mr-2" />
                Export CSV
              </Button>
            </div>

            {[
              {
                id: "1",
                label: "Processors",
                icon: <Hash className="h-5 w-5" />,
              },
              {
                id: "2",
                label: "Motherboard",
                icon: <Building2 className="h-5 w-5" />,
              },
              {
                id: "3",
                label: "Memory (RAM)",
                icon: <Activity className="h-5 w-5" />,
              },
              { id: "4", label: "Storage", icon: <Save className="h-5 w-5" /> },
              {
                id: "5",
                label: "Graphics Card",
                icon: <ImageIcon className="h-5 w-5" />,
              },
              {
                id: "6",
                label: "Power Supply",
                icon: <Zap className="h-5 w-5" />,
              },
              { id: "7", label: "Case", icon: <Package className="h-5 w-5" /> },
              {
                id: "8",
                label: "Cooling",
                icon: <RefreshCw className="h-5 w-5" />,
              },
            ].map((cat) => {
              const categoryItems = filteredComponents.filter(
                (c) => c.component_categories?.category_name === cat.label,
              );

              return (
                <Card
                  key={cat.id}
                  className="border-slate-200 dark:border-slate-800 overflow-hidden shadow-sm"
                >
                  <div className="flex items-center justify-between p-4 bg-white dark:bg-slate-900 border-b">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-slate-100 dark:bg-slate-800 rounded-lg text-slate-600 dark:text-slate-400">
                        {cat.icon}
                      </div>
                      <div>
                        <CardTitle className="text-lg font-bold">
                          {cat.label}
                        </CardTitle>
                        <CardDescription>
                          {categoryItems.length} items registered
                        </CardDescription>
                      </div>
                    </div>

                    <Button
                      size="sm"
                      className="bg-blue-600 hover:bg-blue-700 text-white shadow-sm"
                      onClick={() => {
                        setNewComponentForm({
                          ...newComponentForm,
                          category_id: cat.id,
                        });
                        setCreateComponentDialog(true);
                      }}
                    >
                      <Plus className="h-4 w-4 mr-2" /> Add {cat.label}
                    </Button>
                  </div>

                  <CardContent className="p-0">
                    <div className="overflow-x-auto">
                      <table className="w-full text-sm text-left">
                        <thead className="bg-slate-50 dark:bg-slate-800/50 text-slate-500 font-medium border-b">
                          <tr>
                            <th className="p-4 w-12">Select</th>
                            <th className="p-4">Component Name</th>
                            <th className="p-4">Brand</th>
                            <th className="p-4">Price</th>
                            <th className="p-4 text-right">Actions</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                          {categoryItems.length > 0 ? (
                            categoryItems.map((item) => (
                              <tr
                                key={item.component_id}
                                className="hover:bg-slate-50/50 dark:hover:bg-slate-800/30 transition-colors"
                              >
                                <td className="p-4 text-center">
                                  <Checkbox
                                    checked={selectedItems.includes(
                                      item.component_id,
                                    )}
                                    onCheckedChange={() =>
                                      toggleSelectItem(item.component_id)
                                    }
                                  />
                                </td>
                                <td className="p-4">
                                  <div className="flex items-center gap-3">
                                    {item.component_image && (
                                      <img
                                        src={item.component_image}
                                        className="w-8 h-8 rounded object-cover border"
                                      />
                                    )}
                                    <span className="font-medium">
                                      {item.component_name}
                                    </span>
                                  </div>
                                </td>
                                <td className="p-4 text-muted-foreground">
                                  {item.component_brand || "—"}
                                </td>
                                <td className="p-4 font-semibold text-blue-600">
                                  {formatCurrency(item.component_price || 0)}
                                </td>
                                <td className="p-4 text-right">
                                  <div className="flex justify-end gap-2">
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      onClick={() =>
                                        setEditComponentDialog({
                                          open: true,
                                          component: item,
                                          form: {
                                            component_name: item.component_name,
                                            component_brand:
                                              item.component_brand || "",
                                            component_price:
                                              item.component_price?.toString() ||
                                              "",
                                            component_description:
                                              item.component_description || "",
                                            component_image:
                                              item.component_image || "",
                                          },
                                        })
                                      }
                                    >
                                      <Edit className="h-4 w-4" />
                                    </Button>
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="text-red-500 hover:bg-red-50"
                                      onClick={() =>
                                        setDeleteDialog({
                                          open: true,
                                          type: "component",
                                          id: item.component_id,
                                          name: item.component_name,
                                        })
                                      }
                                    >
                                      <Trash2 className="h-4 w-4" />
                                    </Button>
                                  </div>
                                </td>
                              </tr>
                            ))
                          ) : (
                            <tr>
                              <td
                                colSpan={5}
                                className="p-8 text-center text-muted-foreground italic"
                              >
                                No {cat.label} found in inventory.
                              </td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </TabsContent>

          {/* ==================== PURCHASES TAB ==================== */}
          <TabsContent value="purchases" className="space-y-4">
            <div className="relative max-w-sm">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search purchases..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-8"
              />
            </div>
            <Card>
              <CardHeader>
                <CardTitle>Purchase History</CardTitle>
                <CardDescription>
                  All purchases — emails sent to sales.centraljuan.net@gmail.com
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {purchases
                    .filter((p) =>
                      p.build_name
                        .toLowerCase()
                        .includes(searchTerm.toLowerCase()),
                    )
                    .map((purchase) => (
                      <Card
                        key={purchase.build_id}
                        className="border-l-4 border-l-amber-500"
                      >
                        <CardContent className="pt-4">
                          <div className="flex justify-between items-start">
                            <div className="flex-1">
                              <div className="font-semibold text-lg">
                                {purchase.build_name}
                              </div>
                              <div className="text-sm text-muted-foreground mt-1">
                                Customer:{" "}
                                {purchase.users?.user_name || "Unknown"} (
                                {purchase.users?.email || "N/A"})
                              </div>
                              <div className="text-sm text-muted-foreground">
                                Build Type:{" "}
                                {purchase.build_types?.type_name || "Custom"}
                              </div>
                              <div className="text-xs text-muted-foreground mt-1">
                                {new Date(
                                  purchase.date_created,
                                ).toLocaleString()}
                              </div>
                              <div className="flex gap-2 mt-2">
                                <Badge variant="outline" className="text-xs">
                                  <Mail className="h-3 w-3 mr-1" />
                                  Email Sent
                                </Badge>
                                <Badge variant="secondary" className="text-xs">
                                  sales.centraljuan.net@gmail.com
                                </Badge>
                              </div>
                            </div>
                            <div className="text-right">
                              <div className="font-bold text-2xl text-amber-600">
                                {formatCurrency(purchase.total_price)}
                              </div>
                              <Button
                                variant="outline"
                                size="sm"
                                asChild
                                className="mt-2"
                              >
                                <Link href={`/builds/${purchase.build_id}?fromAdmin=1`}>
                                  <Eye className="h-4 w-4 mr-2" />
                                  View Build
                                </Link>
                              </Button>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* ==================== ACTIVITY TAB ==================== */}
          <TabsContent value="activity" className="space-y-4">
            <div className="flex gap-2">
              <Select
                value={activityTypeFilter}
                onValueChange={setActivityTypeFilter}
              >
                <SelectTrigger className="w-48">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Activities</SelectItem>
                  <SelectItem value="login">Logins</SelectItem>
                  <SelectItem value="logout">Logouts</SelectItem>
                  <SelectItem value="build_created">Build Created</SelectItem>
                  <SelectItem value="build_updated">Build Updated</SelectItem>
                  <SelectItem value="component_viewed">
                    Component Viewed
                  </SelectItem>
                  <SelectItem value="guide_viewed">Guide Viewed</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="h-5 w-5" />
                  User Activity Log
                </CardTitle>
                <CardDescription>
                  Monitor all platform activities ({filteredActivity.length}{" "}
                  records)
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-2 max-h-[600px] overflow-y-auto">
                  {filteredActivity.map((activity) => (
                    <div
                      key={activity.activity_id}
                      className="border rounded-lg p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50"
                    >
                      <div className="flex items-start justify-between gap-4">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <Badge variant="outline">
                              {activity.activity_type}
                            </Badge>
                            <span className="font-medium text-sm">
                              {activity.users?.user_name || "Unknown"}
                            </span>
                            <span className="text-xs text-muted-foreground">
                              {activity.users?.email || "N/A"}
                            </span>
                          </div>
                          <p className="text-sm text-slate-600 dark:text-slate-400">
                            {activity.activity_description}
                          </p>
                          <div className="flex gap-4 mt-2 text-xs text-muted-foreground">
                            <span>
                              {new Date(activity.created_at).toLocaleString()}
                            </span>
                            {activity.ip_address && (
                              <span>IP: {activity.ip_address}</span>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                  {filteredActivity.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      No activity found
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* ==================== AUDIT LOG TAB ==================== */}
          <TabsContent value="audit" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5" />
                  Admin Audit Log
                </CardTitle>
                <CardDescription>
                  Who did what: delete user, update component, etc. (last 150 entries)
                </CardDescription>
              </CardHeader>
              <CardContent>
                {auditLogsLoading ? (
                  <div className="flex items-center justify-center py-12">
                    <Activity className="h-10 w-10 animate-spin text-amber-600" />
                  </div>
                ) : (
                  <div className="space-y-2 max-h-[600px] overflow-y-auto">
                    {auditLogs.map((entry) => (
                      <div
                        key={entry.id}
                        className="border rounded-lg p-3 hover:bg-slate-50 dark:hover:bg-slate-800/50 text-sm"
                      >
                        <div className="flex flex-wrap items-center gap-2">
                          <Badge variant="outline">{entry.action}</Badge>
                          <span className="font-medium">
                            {entry.admin_user?.user_name || `User #${entry.admin_user_id}`}
                          </span>
                          <span className="text-muted-foreground">
                            {entry.target_type}
                            {entry.target_id != null && ` #${entry.target_id}`}
                            {entry.target_name && ` "${entry.target_name}"`}
                          </span>
                        </div>
                        <div className="mt-1 text-xs text-muted-foreground">
                          {new Date(entry.created_at).toLocaleString()}
                          {entry.details && Object.keys(entry.details).length > 0 && (
                            <span className="ml-2">
                              · {JSON.stringify(entry.details)}
                            </span>
                          )}
                        </div>
                      </div>
                    ))}
                    {filteredAuditLogs.length === 0 && !auditLogsLoading && (
                      <div className="text-center py-8 text-muted-foreground">
                        No audit entries yet. Actions you take (delete user, update component, etc.) will appear here.
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* ==================== SETTINGS TAB ==================== */}
          <TabsContent value="settings" className="space-y-6 sm:space-y-8">
            <div className="w-full max-w-4xl mx-auto px-1 sm:px-0">
              {/* SETTINGS HEADER */}
              <div className="mb-2">
                <h2 className="text-xl sm:text-2xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                  <Settings className="h-6 w-6 shrink-0 text-amber-600 dark:text-amber-400" />
                  Settings
                </h2>
                <p className="text-sm text-muted-foreground mt-1">
                  Manage dashboard preferences, notifications, and account
                </p>
              </div>

              {/* DISPLAY PREFERENCES – collapsible */}
              <Collapsible defaultOpen={true}>
                <Card className="overflow-hidden border border-border shadow-sm">
                  <CollapsibleTrigger asChild>
                    <CardHeader className="group p-4 sm:p-5 cursor-pointer hover:bg-slate-50/80 dark:hover:bg-slate-800/50 transition-colors select-none">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2 text-left">
                          <Monitor className="h-5 w-5 shrink-0 text-muted-foreground" />
                          <CardTitle className="text-base sm:text-lg">
                            Display Preferences
                          </CardTitle>
                        </div>
                        <ChevronDown className="h-5 w-5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
                      </div>
                      <CardDescription className="text-sm text-left">
                        Theme, items per page, and refresh interval
                      </CardDescription>
                    </CardHeader>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <CardContent className="space-y-6 p-4 sm:p-5 pt-0 border-t border-border">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div className="space-y-2">
                      <Label>Theme</Label>
                      <Select
                        value={settings.theme}
                        onValueChange={handleThemeChange}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="light">
                            <div className="flex items-center gap-2">
                              <Sun className="h-4 w-4" />
                              Light
                            </div>
                          </SelectItem>
                          <SelectItem value="dark">
                            <div className="flex items-center gap-2">
                              <Moon className="h-4 w-4" />
                              Dark
                            </div>
                          </SelectItem>
                          <SelectItem value="auto">
                            <div className="flex items-center gap-2">
                              <Monitor className="h-4 w-4" />
                              Auto
                            </div>
                          </SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Items Per Page</Label>
                      <Select
                        value={settings.itemsPerPage.toString()}
                        onValueChange={(value) =>
                          setSettings({
                            ...settings,
                            itemsPerPage: parseInt(value),
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="5">5 items</SelectItem>
                          <SelectItem value="10">10 items</SelectItem>
                          <SelectItem value="25">25 items</SelectItem>
                          <SelectItem value="50">50 items</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Auto-Refresh Interval</Label>
                      <Select
                        value={settings.autoRefreshInterval.toString()}
                        onValueChange={(value) =>
                          setSettings({
                            ...settings,
                            autoRefreshInterval: parseInt(value),
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="60000">1 minute</SelectItem>
                          <SelectItem value="300000">5 minutes</SelectItem>
                          <SelectItem value="600000">10 minutes</SelectItem>
                          <SelectItem value="0">Disabled</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Default Export Format</Label>
                      <Select
                        value={settings.defaultExportFormat}
                        onValueChange={(value) =>
                          setSettings({
                            ...settings,
                            defaultExportFormat: value as any,
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="json">JSON</SelectItem>
                          <SelectItem value="csv">CSV</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                    </CardContent>
                  </CollapsibleContent>
                </Card>
              </Collapsible>

              {/* NOTIFICATIONS & ALERTS – collapsible */}
              <Collapsible defaultOpen={false}>
                <Card className="overflow-hidden border border-border shadow-sm">
                  <CollapsibleTrigger asChild>
                    <CardHeader className="group p-4 sm:p-5 cursor-pointer hover:bg-slate-50/80 dark:hover:bg-slate-800/50 transition-colors select-none">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2 text-left">
                          <Bell className="h-5 w-5 shrink-0 text-muted-foreground" />
                          <CardTitle className="text-base sm:text-lg">
                            Notifications & Alerts
                          </CardTitle>
                        </div>
                        <ChevronDown className="h-5 w-5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
                      </div>
                      <CardDescription className="text-sm text-left">
                        Alert email and notification toggles
                      </CardDescription>
                    </CardHeader>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <CardContent className="space-y-4 p-4 sm:p-5 pt-0 border-t border-border">
                  <div className="space-y-2">
                    <Label htmlFor="notif-email">Alert Email Address</Label>
                    <div className="flex flex-col sm:flex-row gap-2">
                      <Input
                        id="notif-email"
                        type="email"
                        placeholder="admin@example.com"
                        value={settings.notificationEmail}
                        onChange={(e) =>
                          setSettings({
                            ...settings,
                            notificationEmail: e.target.value,
                          })
                        }
                        className="w-full min-w-0"
                      />
                      <div className="flex gap-2 shrink-0">
                        <Button
                          variant="ghost"
                          size="sm"
                          className="flex-1 sm:flex-none"
                          onClick={() =>
                            handleCopyField(settings.notificationEmail, "email")
                          }
                          disabled={!settings.notificationEmail}
                        >
                          {copiedField === "email" ? (
                            <Check className="h-4 w-4" />
                          ) : (
                            <Copy className="h-4 w-4" />
                          )}
                        </Button>
                        <Button
                          size="sm"
                          className="flex-1 sm:flex-none"
                          onClick={handleSendTestEmail}
                          disabled={!settings.notificationEmail || actionLoading}
                        >
                          {actionLoading ? (
                            <Loader className="h-4 w-4 animate-spin" />
                          ) : (
                            "Test"
                          )}
                        </Button>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-3 border-t pt-4">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 py-1">
                      <Label className="text-sm">Purchase Notifications</Label>
                      <Checkbox
                        checked={settings.purchaseNotifications}
                        onCheckedChange={(checked) =>
                          setSettings({
                            ...settings,
                            purchaseNotifications: !!checked,
                          })
                        }
                        className="shrink-0"
                      />
                    </div>

                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 py-1">
                      <Label className="text-sm">Daily Activity Report</Label>
                      <Checkbox
                        checked={settings.dailyActivityReport}
                        onCheckedChange={(checked) =>
                          setSettings({
                            ...settings,
                            dailyActivityReport: !!checked,
                          })
                        }
                        className="shrink-0"
                      />
                    </div>

                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 py-1">
                      <Label className="text-sm">User Registration Alerts</Label>
                      <Checkbox
                        checked={settings.userRegistrationAlerts}
                        onCheckedChange={(checked) =>
                          setSettings({
                            ...settings,
                            userRegistrationAlerts: !!checked,
                          })
                        }
                        className="shrink-0"
                      />
                    </div>
                  </div>
                    </CardContent>
                  </CollapsibleContent>
                </Card>
              </Collapsible>

              {/* SECURITY SETTINGS – collapsible */}
              <Collapsible defaultOpen={false}>
                <Card className="overflow-hidden border border-border shadow-sm">
                  <CollapsibleTrigger asChild>
                    <CardHeader className="group p-4 sm:p-5 cursor-pointer hover:bg-slate-50/80 dark:hover:bg-slate-800/50 transition-colors select-none">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2 text-left">
                          <Lock className="h-5 w-5 shrink-0 text-muted-foreground" />
                          <CardTitle className="text-base sm:text-lg">
                            Security Settings
                          </CardTitle>
                        </div>
                        <ChevronDown className="h-5 w-5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
                      </div>
                      <CardDescription className="text-sm text-left">
                        Session timeout, confirmations, and password
                      </CardDescription>
                    </CardHeader>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <CardContent className="space-y-4 p-4 sm:p-5 pt-0 border-t border-border">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="session-timeout" className="text-sm">
                        Session Timeout (minutes)
                      </Label>
                      <Input
                        id="session-timeout"
                        type="number"
                        min="5"
                        max="480"
                        value={settings.sessionTimeout}
                        onChange={(e) =>
                          setSettings({
                            ...settings,
                            sessionTimeout: parseInt(e.target.value),
                          })
                        }
                        className="w-full"
                      />
                    </div>
                  </div>

                  <div className="space-y-3 border-t pt-4">
                    <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 py-1">
                      <div className="min-w-0 flex-1">
                        <Label className="text-sm">Require Confirmation for Deletions</Label>
                        <p className="text-xs text-muted-foreground mt-1">
                          Ask for confirmation before deleting any items
                        </p>
                      </div>
                      <Checkbox
                        checked={settings.requireDeleteConfirm}
                        onCheckedChange={(checked) =>
                          setSettings({
                            ...settings,
                            requireDeleteConfirm: !!checked,
                          })
                        }
                        className="shrink-0 mt-1 sm:mt-0"
                      />
                    </div>

                    <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 py-1">
                      <div className="min-w-0 flex-1">
                        <Label className="text-sm">Enable Activity Logging</Label>
                        <p className="text-xs text-muted-foreground mt-1">
                          Log all admin actions for audit trail
                        </p>
                      </div>
                      <Checkbox
                        checked={settings.enableActivityLogging}
                        onCheckedChange={(checked) =>
                          setSettings({
                            ...settings,
                            enableActivityLogging: !!checked,
                          })
                        }
                        className="shrink-0 mt-1 sm:mt-0"
                      />
                    </div>
                  </div>

                  <Button
                    variant="outline"
                    className="w-full mt-4 min-h-11 inline-flex items-center justify-center gap-2"
                    onClick={() => setChangePasswordDialog(true)}
                  >
                    <Lock className="h-4 w-4 shrink-0" />
                    Change Admin Password
                  </Button>
                    </CardContent>
                  </CollapsibleContent>
                </Card>
              </Collapsible>

              {/* Section label */}
              <div className="pt-2 pb-1">
                <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
                  Account & Data
                </p>
              </div>

              {/* ACCOUNT & SESSION – collapsible */}
              <Collapsible defaultOpen={false}>
                <Card className="overflow-hidden border border-border shadow-sm">
                  <CollapsibleTrigger asChild>
                    <CardHeader className="group p-4 sm:p-5 cursor-pointer hover:bg-slate-50/80 dark:hover:bg-slate-800/50 transition-colors select-none">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2 text-left">
                          <User className="h-5 w-5 shrink-0 text-muted-foreground" />
                          <CardTitle className="text-base sm:text-lg">
                            Account & Session
                          </CardTitle>
                        </div>
                        <ChevronDown className="h-5 w-5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
                      </div>
                      <CardDescription className="text-sm text-left">
                        Logged-in user and logout
                      </CardDescription>
                    </CardHeader>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <CardContent className="space-y-4 p-4 sm:p-5 pt-0 border-t border-border">
                      <div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                        <p className="text-sm text-blue-900 dark:text-blue-200 break-words">
                          <span className="font-semibold">Logged in as:</span>{" "}
                          {user?.user_name || user?.email}
                        </p>
                      </div>

                      <Button
                        variant="destructive"
                        className="w-full min-h-11 inline-flex items-center justify-center gap-2"
                        onClick={handleLogout}
                        disabled={actionLoading}
                      >
                        {actionLoading ? (
                          <>
                            <Loader className="h-4 w-4 shrink-0 animate-spin" />
                            Logging out...
                          </>
                        ) : (
                          <>
                            <LogOut className="h-4 w-4 shrink-0" />
                            Logout
                          </>
                        )}
                      </Button>
                    </CardContent>
                  </CollapsibleContent>
                </Card>
              </Collapsible>

              {/* DATA MANAGEMENT – collapsible */}
              <Collapsible defaultOpen={false}>
                <Card className="overflow-hidden border border-border shadow-sm">
                  <CollapsibleTrigger asChild>
                    <CardHeader className="group p-4 sm:p-5 cursor-pointer hover:bg-slate-50/80 dark:hover:bg-slate-800/50 transition-colors select-none">
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2 text-left">
                          <Download className="h-5 w-5 shrink-0 text-muted-foreground" />
                          <CardTitle className="text-base sm:text-lg">
                            Data Management
                          </CardTitle>
                        </div>
                        <ChevronDown className="h-5 w-5 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
                      </div>
                      <CardDescription className="text-sm text-left">
                        Export, backup, restore, and clear logs
                      </CardDescription>
                    </CardHeader>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <CardContent className="space-y-3 p-4 sm:p-5 pt-0 border-t border-border">
                      <Button
                        variant="outline"
                        className="w-full min-h-11 inline-flex items-center justify-center gap-2"
                        onClick={handleExportAllData}
                        disabled={actionLoading}
                      >
                        {actionLoading ? (
                          <>
                            <Loader className="h-4 w-4 shrink-0 animate-spin" />
                            Exporting...
                          </>
                        ) : (
                          <>
                            <Download className="h-4 w-4 shrink-0" />
                            Export All Data
                          </>
                        )}
                      </Button>

                      <div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                        <p className="text-sm text-blue-900 dark:text-blue-200 break-words">
                          <span className="font-semibold">Current Data:</span>{" "}
                          {stats.totalUsers} users • {stats.totalBuilds} builds •{" "}
                          {stats.totalComponents} components
                        </p>
                      </div>

                      <div className="space-y-2 border-t pt-4">
                        <Button
                          variant="outline"
                          className="w-full min-h-11 inline-flex items-center justify-center gap-2"
                          onClick={handleBackupSettings}
                        >
                          <Save className="h-4 w-4 shrink-0" />
                          Backup Settings
                        </Button>

                        <Button
                          variant="outline"
                          className="w-full min-h-11 inline-flex items-center justify-center gap-2"
                          onClick={handleRestoreSettings}
                        >
                          <RotateCcw className="h-4 w-4 shrink-0" />
                          Restore Settings
                        </Button>
                      </div>

                      <Button
                        variant="destructive"
                        className="w-full min-h-11 inline-flex items-center justify-center gap-2"
                        onClick={() => setClearLogsDialog(true)}
                      >
                        <Trash2 className="h-4 w-4 shrink-0" />
                        Clear Activity Logs
                      </Button>
                    </CardContent>
                  </CollapsibleContent>
                </Card>
              </Collapsible>

              {/* SAVE / RESET BAR */}
              <div className="sticky bottom-0 left-0 right-0 z-10 mt-8 pt-6 pb-2 bg-gradient-to-t from-background via-background to-transparent border-t border-border">
                <div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-3">
                  <Button
                    variant="outline"
                    onClick={handleResetSettings}
                    className="w-full sm:w-auto min-h-11 inline-flex items-center justify-center gap-2"
                  >
                    Reset to Defaults
                  </Button>
                  <Button
                    onClick={handleSaveSettings}
                    className="w-full sm:w-auto min-h-11 bg-amber-600 hover:bg-amber-700 inline-flex items-center justify-center gap-2"
                    disabled={settingsSaved}
                  >
                    {settingsSaved ? (
                      <>
                        <Check className="h-4 w-4 shrink-0" />
                        Settings Saved
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4 shrink-0" />
                        Save Settings
                      </>
                    )}
                  </Button>
                </div>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </div>

      {/* ================================================================
          ==================== ALL DIALOGS BELOW ==========================
          ================================================================ */}

      {/* DELETE CONFIRMATION DIALOG */}
      <AlertDialog
        open={deleteDialog.open}
        onOpenChange={(open) => setDeleteDialog({ ...deleteDialog, open })}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete {deleteDialog.type}{" "}
              <span className="font-semibold text-slate-900 dark:text-white">
                "{deleteDialog.name}"
              </span>
              . This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (deleteDialog.type === "user") handleDeleteUser();
                if (deleteDialog.type === "build") handleDeleteBuild();
                if (deleteDialog.type === "component") handleDeleteComponent();
              }}
              className="bg-red-600 hover:bg-red-700"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* BULK DELETE CONFIRMATION */}
      {bulkAction === "delete" && (
        <AlertDialog open={true} onOpenChange={() => setBulkAction("")}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>
                Delete {selectedItems.length} items?
              </AlertDialogTitle>
              <AlertDialogDescription>
                This will permanently delete the selected items. This action
                cannot be undone.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleBulkAction}
                className="bg-red-600 hover:bg-red-700"
              >
                Delete All
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}

      {/* CHANGE PASSWORD DIALOG */}
      <Dialog
        open={changePasswordDialog}
        onOpenChange={setChangePasswordDialog}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Lock className="h-5 w-5 text-amber-600" />
              Change Password
            </DialogTitle>
            <DialogDescription>
              Update your admin account password
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Current Password</Label>
              <div className="relative">
                <Input
                  type={showPasswords.current ? "text" : "password"}
                  placeholder="Enter current password"
                  value={passwordForm.current}
                  onChange={(e) =>
                    setPasswordForm({
                      ...passwordForm,
                      current: e.target.value,
                    })
                  }
                />
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute right-2 top-1/2 -translate-y-1/2"
                  onClick={() =>
                    setShowPasswords({
                      ...showPasswords,
                      current: !showPasswords.current,
                    })
                  }
                >
                  {showPasswords.current ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <EyeIcon className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
            <div className="space-y-2">
              <Label>New Password</Label>
              <div className="relative">
                <Input
                  type={showPasswords.new ? "text" : "password"}
                  placeholder="Enter new password (min 8 characters)"
                  value={passwordForm.new}
                  onChange={(e) =>
                    setPasswordForm({ ...passwordForm, new: e.target.value })
                  }
                />
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute right-2 top-1/2 -translate-y-1/2"
                  onClick={() =>
                    setShowPasswords({
                      ...showPasswords,
                      new: !showPasswords.new,
                    })
                  }
                >
                  {showPasswords.new ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <EyeIcon className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Confirm New Password</Label>
              <div className="relative">
                <Input
                  type={showPasswords.confirm ? "text" : "password"}
                  placeholder="Confirm new password"
                  value={passwordForm.confirm}
                  onChange={(e) =>
                    setPasswordForm({
                      ...passwordForm,
                      confirm: e.target.value,
                    })
                  }
                />
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute right-2 top-1/2 -translate-y-1/2"
                  onClick={() =>
                    setShowPasswords({
                      ...showPasswords,
                      confirm: !showPasswords.confirm,
                    })
                  }
                >
                  {showPasswords.confirm ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <EyeIcon className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setChangePasswordDialog(false);
                setPasswordForm({ current: "", new: "", confirm: "" });
              }}
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={handleChangePassword}
              disabled={actionLoading}
              className="bg-amber-600 hover:bg-amber-700"
            >
              {actionLoading ? (
                <Loader className="h-4 w-4 animate-spin mr-2" />
              ) : (
                <Save className="h-4 w-4 mr-2" />
              )}
              Change Password
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* CLEAR LOGS DIALOG */}
      <AlertDialog open={clearLogsDialog} onOpenChange={setClearLogsDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Clear all activity logs?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete all activity logs. This action cannot
              be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleClearActivityLogs}
              className="bg-red-600 hover:bg-red-700"
            >
              Clear Logs
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* CREATE USER DIALOG */}
      <Dialog
        open={createUserDialog}
        onOpenChange={(open) => {
          if (!open) setCreateUserDialog(false);
        }}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Users className="h-5 w-5 text-amber-600" />
              Create New User
            </DialogTitle>
            <DialogDescription>
              Add a new user account to the platform.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="new-username">
                <User className="h-4 w-4 inline mr-1" />
                Username <span className="text-red-500">*</span>
              </Label>
              <Input
                id="new-username"
                placeholder="e.g. juan_dela_cruz"
                value={newUserForm.user_name}
                onChange={(e) =>
                  setNewUserForm({ ...newUserForm, user_name: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="new-email">
                <Mail className="h-4 w-4 inline mr-1" />
                Email <span className="text-red-500">*</span>
              </Label>
              <Input
                id="new-email"
                type="email"
                placeholder="user@example.com"
                value={newUserForm.email}
                onChange={(e) =>
                  setNewUserForm({ ...newUserForm, email: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="new-password">
                Password <span className="text-red-500">*</span>
              </Label>
              <Input
                id="new-password"
                type="password"
                placeholder="••••••••"
                value={newUserForm.password}
                onChange={(e) =>
                  setNewUserForm({ ...newUserForm, password: e.target.value })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Role</Label>
              <Select
                value={newUserForm.user_type}
                onValueChange={(val) =>
                  setNewUserForm({ ...newUserForm, user_type: val as any })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="user">
                    <div className="flex items-center gap-2">
                      <User className="h-4 w-4" />
                      User
                    </div>
                  </SelectItem>
                  <SelectItem value="moderator">
                    <div className="flex items-center gap-2">
                      <Star className="h-4 w-4" />
                      Moderator
                    </div>
                  </SelectItem>
                  <SelectItem value="admin">
                    <div className="flex items-center gap-2">
                      <Shield className="h-4 w-4" />
                      Admin
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setCreateUserDialog(false)}
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={handleCreateUser}
              disabled={actionLoading}
              className="bg-amber-600 hover:bg-amber-700"
            >
              {actionLoading ? (
                "Creating..."
              ) : (
                <>
                  <Plus className="h-4 w-4 mr-2" />
                  Create User
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* EDIT USER DIALOG */}
      <Dialog
        open={editUserDialog.open}
        onOpenChange={(open) => {
          if (!open)
            setEditUserDialog({
              open: false,
              user: null,
              userType: "",
              userName: "",
              email: "",
            });
        }}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="h-5 w-5 text-amber-600" />
              Edit User
            </DialogTitle>
            <DialogDescription>
              Update details for {editUserDialog.user?.user_name}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>
                Username <span className="text-red-500">*</span>
              </Label>
              <Input
                placeholder="Username"
                value={editUserDialog.userName}
                onChange={(e) =>
                  setEditUserDialog({
                    ...editUserDialog,
                    userName: e.target.value,
                  })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>
                Email <span className="text-red-500">*</span>
              </Label>
              <Input
                type="email"
                placeholder="Email"
                value={editUserDialog.email}
                onChange={(e) =>
                  setEditUserDialog({
                    ...editUserDialog,
                    email: e.target.value,
                  })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Role</Label>
              <Select
                value={editUserDialog.userType}
                onValueChange={(val) =>
                  setEditUserDialog({ ...editUserDialog, userType: val })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="admin">
                    <div className="flex items-center gap-2">
                      <Shield className="h-4 w-4" />
                      Admin
                    </div>
                  </SelectItem>
                  <SelectItem value="moderator">
                    <div className="flex items-center gap-2">
                      <Star className="h-4 w-4" />
                      Moderator
                    </div>
                  </SelectItem>
                  <SelectItem value="user">
                    <div className="flex items-center gap-2">
                      <User className="h-4 w-4" />
                      User
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() =>
                setEditUserDialog({
                  open: false,
                  user: null,
                  userType: "",
                  userName: "",
                  email: "",
                })
              }
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button onClick={handleUpdateUser} disabled={actionLoading}>
              {actionLoading ? (
                "Saving..."
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  Save Changes
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* EDIT BUILD NAME DIALOG */}
      <Dialog
        open={editBuildDialog.open}
        onOpenChange={(open) => {
          if (!open)
            setEditBuildDialog({ open: false, build: null, buildName: "" });
        }}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Wrench className="h-5 w-5 text-amber-600" />
              Edit Build
            </DialogTitle>
            <DialogDescription>
              Update the name for this PC build.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>
                Build Name <span className="text-red-500">*</span>
              </Label>
              <Input
                placeholder="e.g. Gaming Beast Pro"
                value={editBuildDialog.buildName}
                onChange={(e) =>
                  setEditBuildDialog({
                    ...editBuildDialog,
                    buildName: e.target.value,
                  })
                }
              />
            </div>
            {editBuildDialog.build && (
              <div className="rounded-lg bg-slate-50 dark:bg-slate-800 p-3 text-sm space-y-1">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Current Price</span>
                  <span className="font-semibold text-amber-600">
                    {formatCurrency(editBuildDialog.build.total_price)}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Created By</span>
                  <span>
                    {editBuildDialog.build.users?.user_name || "Unknown"}
                  </span>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  Note: To edit components/price, open the build in the build
                  editor.
                </p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() =>
                setEditBuildDialog({ open: false, build: null, buildName: "" })
              }
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button onClick={handleUpdateBuildName} disabled={actionLoading}>
              {actionLoading ? (
                "Saving..."
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  Save Name
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* CREATE COMPONENT DIALOG */}
      <Dialog
        open={createComponentDialog}
        onOpenChange={(open) => {
          if (!open) setCreateComponentDialog(false);
        }}
      >
        <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Package className="h-5 w-5 text-amber-600" />
              Add New Component
            </DialogTitle>
            <DialogDescription>
              Add a new PC component to the inventory.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>
                <Hash className="h-4 w-4 inline mr-1" />
                Component Name <span className="text-red-500">*</span>
              </Label>
              <Input
                placeholder="e.g. RTX 4070 Ti SUPER"
                value={newComponentForm.component_name}
                onChange={(e) =>
                  setNewComponentForm({
                    ...newComponentForm,
                    component_name: e.target.value,
                  })
                }
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>
                  <Building2 className="h-4 w-4 inline mr-1" />
                  Brand
                </Label>
                <Input
                  placeholder="e.g. NVIDIA, AMD"
                  value={newComponentForm.component_brand}
                  onChange={(e) =>
                    setNewComponentForm({
                      ...newComponentForm,
                      component_brand: e.target.value,
                    })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>
                  <DollarSign className="h-4 w-4 inline mr-1" />
                  Price (₱)
                </Label>
                <Input
                  type="number"
                  placeholder="e.g. 45000"
                  value={newComponentForm.component_price}
                  onChange={(e) =>
                    setNewComponentForm({
                      ...newComponentForm,
                      component_price: e.target.value,
                    })
                  }
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>
                <FileText className="h-4 w-4 inline mr-1" />
                Description
              </Label>
              <Textarea
                placeholder="Component description..."
                rows={3}
                value={newComponentForm.component_description}
                onChange={(e) =>
                  setNewComponentForm({
                    ...newComponentForm,
                    component_description: e.target.value,
                  })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>
                <ImageIcon className="h-4 w-4 inline mr-1" />
                Image URL
              </Label>
              <Input
                placeholder="https://example.com/image.jpg"
                value={newComponentForm.component_image}
                onChange={(e) =>
                  setNewComponentForm({
                    ...newComponentForm,
                    component_image: e.target.value,
                  })
                }
              />
              <div className="flex items-center gap-2 flex-wrap">
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  id="new-component-image-upload"
                  onChange={async (e) => {
                    const file = e.target.files?.[0];
                    if (!file) return;
                    const url = await uploadComponentImage(file);
                    if (url)
                      setNewComponentForm({
                        ...newComponentForm,
                        component_image: url,
                      });
                    e.target.value = "";
                  }}
                />
                <Label
                  htmlFor="new-component-image-upload"
                  className="cursor-pointer inline-flex items-center gap-1.5 px-3 py-2 rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground text-sm"
                >
                  {imageUploading ? "Uploading…" : "Upload image"}
                </Label>
              </div>
              {newComponentForm.component_image && (
                <div className="border rounded-lg p-3 bg-slate-50 dark:bg-slate-900">
                  <img
                    src={newComponentForm.component_image}
                    alt="Preview"
                    className="w-20 h-20 object-cover rounded mx-auto"
                    onError={(e) => {
                      (e.target as HTMLImageElement).style.display = "none";
                    }}
                  />
                </div>
              )}
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>
                  <Tag className="h-4 w-4 inline mr-1" />
                  Category ID
                </Label>
                <Input
                  type="number"
                  placeholder="Category ID"
                  value={newComponentForm.category_id}
                  onChange={(e) =>
                    setNewComponentForm({
                      ...newComponentForm,
                      category_id: e.target.value,
                    })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>Retailer ID</Label>
                <Input
                  type="number"
                  placeholder="Retailer ID"
                  value={newComponentForm.retailer_id}
                  onChange={(e) =>
                    setNewComponentForm({
                      ...newComponentForm,
                      retailer_id: e.target.value,
                    })
                  }
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setCreateComponentDialog(false)}
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={handleCreateComponent}
              disabled={actionLoading}
              className="bg-amber-600 hover:bg-amber-700"
            >
              {actionLoading ? (
                "Adding..."
              ) : (
                <>
                  <Plus className="h-4 w-4 mr-2" />
                  Add Component
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* EDIT COMPONENT DIALOG */}
      <Dialog
        open={editComponentDialog.open}
        onOpenChange={(open) => {
          if (!open)
            setEditComponentDialog({
              open: false,
              component: null,
              form: {
                component_name: "",
                component_brand: "",
                component_price: "",
                component_description: "",
                component_image: "",
              },
            });
        }}
      >
        <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit className="h-5 w-5 text-amber-600" />
              Edit Component
            </DialogTitle>
            <DialogDescription>
              Update details for {editComponentDialog.component?.component_name}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>
                Component Name <span className="text-red-500">*</span>
              </Label>
              <Input
                placeholder="Component name"
                value={editComponentDialog.form.component_name}
                onChange={(e) =>
                  setEditComponentDialog({
                    ...editComponentDialog,
                    form: {
                      ...editComponentDialog.form,
                      component_name: e.target.value,
                    },
                  })
                }
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Brand</Label>
                <Input
                  placeholder="e.g. NVIDIA, AMD"
                  value={editComponentDialog.form.component_brand}
                  onChange={(e) =>
                    setEditComponentDialog({
                      ...editComponentDialog,
                      form: {
                        ...editComponentDialog.form,
                        component_brand: e.target.value,
                      },
                    })
                  }
                />
              </div>
              <div className="space-y-2">
                <Label>Price (₱)</Label>
                <Input
                  type="number"
                  placeholder="e.g. 45000"
                  value={editComponentDialog.form.component_price}
                  onChange={(e) =>
                    setEditComponentDialog({
                      ...editComponentDialog,
                      form: {
                        ...editComponentDialog.form,
                        component_price: e.target.value,
                      },
                    })
                  }
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                placeholder="Component description..."
                rows={3}
                value={editComponentDialog.form.component_description}
                onChange={(e) =>
                  setEditComponentDialog({
                    ...editComponentDialog,
                    form: {
                      ...editComponentDialog.form,
                      component_description: e.target.value,
                    },
                  })
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Image URL</Label>
              <Input
                placeholder="https://example.com/image.jpg"
                value={editComponentDialog.form.component_image}
                onChange={(e) =>
                  setEditComponentDialog({
                    ...editComponentDialog,
                    form: {
                      ...editComponentDialog.form,
                      component_image: e.target.value,
                    },
                  })
                }
              />
              <div className="flex items-center gap-2 flex-wrap mt-2">
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  id="edit-component-image-upload"
                  onChange={async (e) => {
                    const file = e.target.files?.[0];
                    if (!file) return;
                    const url = await uploadComponentImage(file);
                    if (url)
                      setEditComponentDialog({
                        ...editComponentDialog,
                        form: {
                          ...editComponentDialog.form,
                          component_image: url,
                        },
                      });
                    e.target.value = "";
                  }}
                />
                <Label
                  htmlFor="edit-component-image-upload"
                  className="cursor-pointer inline-flex items-center gap-1.5 px-3 py-2 rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground text-sm"
                >
                  {imageUploading ? "Uploading…" : "Upload image"}
                </Label>
              </div>
              {editComponentDialog.form.component_image && (
                <div className="border rounded-lg p-3 bg-slate-50 dark:bg-slate-900">
                  <img
                    src={editComponentDialog.form.component_image}
                    alt="Preview"
                    className="w-20 h-20 object-cover rounded mx-auto"
                    onError={(e) => {
                      (e.target as HTMLImageElement).style.display = "none";
                    }}
                  />
                </div>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() =>
                setEditComponentDialog({
                  open: false,
                  component: null,
                  form: {
                    component_name: "",
                    component_brand: "",
                    component_price: "",
                    component_description: "",
                    component_image: "",
                  },
                })
              }
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button onClick={handleUpdateComponent} disabled={actionLoading}>
              {actionLoading ? (
                "Saving..."
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  Save Changes
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* EDIT IMAGE DIALOG */}
      <Dialog
        open={editImageDialog.open}
        onOpenChange={(open) => {
          if (!open)
            setEditImageDialog({ open: false, component: null, imageUrl: "" });
        }}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ImageIcon className="h-5 w-5 text-amber-600" />
              Edit Component Image
            </DialogTitle>
            <DialogDescription>
              Update the image URL for{" "}
              {editImageDialog.component?.component_name}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="imageUrl">Image URL</Label>
              <Input
                id="imageUrl"
                placeholder="https://example.com/image.jpg"
                value={editImageDialog.imageUrl}
                onChange={(e) =>
                  setEditImageDialog({
                    ...editImageDialog,
                    imageUrl: e.target.value,
                  })
                }
              />
              <div className="flex items-center gap-2 flex-wrap mt-2">
                <input
                  type="file"
                  accept="image/*"
                  className="hidden"
                  id="edit-image-dialog-upload"
                  onChange={async (e) => {
                    const file = e.target.files?.[0];
                    if (!file) return;
                    const url = await uploadComponentImage(file);
                    if (url)
                      setEditImageDialog({
                        ...editImageDialog,
                        imageUrl: url,
                      });
                    e.target.value = "";
                  }}
                />
                <Label
                  htmlFor="edit-image-dialog-upload"
                  className="cursor-pointer inline-flex items-center gap-1.5 px-3 py-2 rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground text-sm"
                >
                  {imageUploading ? "Uploading…" : "Upload image"}
                </Label>
              </div>
            </div>
            {editImageDialog.imageUrl && (
              <div className="border rounded-lg p-4 bg-slate-50 dark:bg-slate-900">
                <img
                  src={editImageDialog.imageUrl}
                  alt="Preview"
                  className="w-32 h-32 object-cover rounded-lg mx-auto"
                  onError={(e) => {
                    (e.target as HTMLImageElement).style.display = "none";
                  }}
                />
              </div>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() =>
                setEditImageDialog({
                  open: false,
                  component: null,
                  imageUrl: "",
                })
              }
              disabled={actionLoading}
            >
              Cancel
            </Button>
            <Button onClick={handleUpdateImage} disabled={actionLoading}>
              {actionLoading ? "Updating..." : "Update Image"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

/* ==================== STAT CARD COMPONENT ==================== */

interface StatCardProps {
  icon: React.ReactNode;
  label: string;
  value: string | number;
  subtext?: string;
  trend?: number;
  color?: "blue" | "green" | "purple" | "amber" | "red";
}

function StatCard({
  icon,
  label,
  value,
  subtext,
  trend,
  color = "blue",
}: StatCardProps) {
  const colorClasses = {
    blue: "bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400",
    green:
      "bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400",
    purple:
      "bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400",
    amber:
      "bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400",
    red: "bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400",
  };

  return (
    <Card className="border-slate-200 dark:border-slate-700 shadow-sm hover:shadow transition-shadow overflow-hidden">
      <CardContent className="p-4 sm:pt-6 sm:p-6">
        <div className="flex items-start justify-between gap-3">
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-muted-foreground mb-1">
              {label}
            </p>
            <p className="text-2xl sm:text-3xl font-bold mb-1 truncate">{value}</p>
            <div className="flex items-center gap-2">
              {subtext && (
                <p className="text-xs text-muted-foreground">{subtext}</p>
              )}
              {trend !== undefined && (
                <Badge
                  variant={trend >= 0 ? "default" : "destructive"}
                  className="text-xs"
                >
                  {trend >= 0 ? (
                    <TrendingUp className="h-3 w-3 mr-1" />
                  ) : (
                    <TrendingDown className="h-3 w-3 mr-1" />
                  )}
                  {Math.abs(trend)}%
                </Badge>
              )}
            </div>
          </div>
          <div className={`p-3 rounded-lg ${colorClasses[color]}`}>{icon}</div>
        </div>
      </CardContent>
    </Card>
  );
}
