// File: src/components/UIX/UserListItem/UserListItem.jsx

import React, { memo, useMemo, useCallback } from "react";
import { useUIXTheme } from "../themes/useUIXTheme.jsx";

/**
 * UserListItem Component - Performance Optimized
 * Reusable list item for displaying users/members with avatars, badges, and actions
 *
 * Perfect for member lists, user directories, sharing dialogs, or any list
 * where you need to display user information with actions.
 *
 * Performance optimizations:
 * - Component memoization with React.memo
 * - Memoized theme classes to prevent multiple getThemeClasses calls
 * - Optimized event handlers with useCallback
 * - Prevented unnecessary re-renders
 *
 * @param {string} name - User's name or email
 * @param {string} email - User's email (optional, shown as secondary text)
 * @param {string} avatarText - Text to display in avatar (usually first letter of name)
 * @param {string} avatarColor - Avatar background color (gradient class)
 * @param {Array} badges - Array of {label, variant} objects for status badges
 * @param {string} subtitle - Subtitle text (e.g., "Shared 2 days ago")
 * @param {string} rightText - Text to display on the right (e.g., "Full control")
 * @param {React.Component} rightIcon - Icon to display before right text
 * @param {string} rightIconColor - Color class for right icon
 * @param {Array} actions - Array of {icon, label, onClick, variant} for action buttons
 * @param {boolean} highlighted - Whether to highlight this item (e.g., owner, current user)
 * @param {string} highlightColor - Color for highlight (defaults to accent)
 * @param {string} className - Additional CSS classes
 */
const UserListItem = memo(function UserListItem({
  name,
  email,
  avatarText,
  avatarColor,
  badges = [],
  subtitle,
  rightText,
  rightIcon: RightIcon,
  rightIconColor,
  actions = [],
  highlighted = false,
  highlightColor,
  className = "",
}) {
  const { getThemeClasses } = useUIXTheme();

  // Memoize all theme classes
  const themeClasses = useMemo(
    () => ({
      textPrimary: getThemeClasses("text-primary"),
      textSecondary: getThemeClasses("text-secondary"),
      textMuted: getThemeClasses("text-muted"),
      bgCard: getThemeClasses("bg-card"),
      bgMuted: getThemeClasses("bg-muted"),
      bgGradientSecondary: getThemeClasses("bg-gradient-secondary"),
      bgGradientAccent: getThemeClasses("bg-gradient-accent"),
      bgAccentLight: getThemeClasses("bg-accent-light"),
      bgSuccessLight: getThemeClasses("bg-success-light"),
      borderSecondary: getThemeClasses("border-secondary"),
      borderAccent: getThemeClasses("border-accent"),
      borderSuccess: getThemeClasses("border-success"),
      textAccent: getThemeClasses("text-accent"),
      textSuccess: getThemeClasses("text-success"),
      textError: getThemeClasses("text-error"),
      hoverTextError: getThemeClasses("hover:text-error"),
      hoverBgErrorLight: getThemeClasses("hover:bg-error-light"),
    }),
    [getThemeClasses],
  );

  // Determine container styling based on highlighted state
  const containerClasses = useMemo(() => {
    const baseClasses = `p-4 rounded-lg hover:shadow-sm transition-all duration-200`;

    if (highlighted) {
      const bgClass = highlightColor === "success"
        ? themeClasses.bgSuccessLight
        : themeClasses.bgGradientAccent;
      const borderClass = highlightColor === "success"
        ? themeClasses.borderSuccess
        : themeClasses.borderAccent;
      return `${baseClasses} ${bgClass} border ${borderClass}`;
    }

    return `${baseClasses} ${themeClasses.bgCard} border ${themeClasses.borderSecondary}`;
  }, [highlighted, highlightColor, themeClasses]);

  // Get badge styling
  const getBadgeClasses = useCallback((variant) => {
    const baseClasses = "text-xs font-medium px-2 py-0.5 rounded-full";
    switch (variant) {
      case "accent":
        return `${baseClasses} ${themeClasses.bgAccentLight} ${themeClasses.textAccent}`;
      case "success":
        return `${baseClasses} ${themeClasses.bgSuccessLight} ${themeClasses.textSuccess}`;
      case "muted":
        return `${baseClasses} ${themeClasses.bgMuted} ${themeClasses.textSecondary}`;
      default:
        return `${baseClasses} ${themeClasses.bgMuted} ${themeClasses.textPrimary}`;
    }
  }, [themeClasses]);

  // Get action button styling
  const getActionButtonClasses = useCallback((variant) => {
    const baseClasses = "p-2 rounded-lg transition-all duration-200";
    if (variant === "danger") {
      return `${baseClasses} ${themeClasses.textMuted} ${themeClasses.hoverTextError} ${themeClasses.hoverBgErrorLight}`;
    }
    return `${baseClasses} ${themeClasses.textMuted} hover:${themeClasses.textPrimary} ${themeClasses.hoverBgMuted}`;
  }, [themeClasses]);

  return (
    <div className={`${containerClasses} ${className}`}>
      <div className="flex items-center justify-between">
        {/* Left: Avatar and Info */}
        <div className="flex items-center space-x-3">
          {/* Avatar */}
          <div
            className={`h-10 w-10 rounded-full flex items-center justify-center text-white font-semibold ${
              avatarColor || themeClasses.bgGradientSecondary
            }`}
          >
            {avatarText || "?"}
          </div>

          {/* Name, Email, Badges, Subtitle */}
          <div>
            <div className="flex items-center space-x-2">
              <p className={`font-medium ${themeClasses.textPrimary}`}>
                {name}
              </p>
              {badges.map((badge, index) => (
                <span key={index} className={getBadgeClasses(badge.variant)}>
                  {badge.label}
                </span>
              ))}
            </div>
            {(email || subtitle) && (
              <p className={`text-sm ${themeClasses.textSecondary}`}>
                {subtitle || email}
              </p>
            )}
          </div>
        </div>

        {/* Right: Info Text and Actions */}
        <div className="flex items-center space-x-3">
          {/* Right Text/Icon */}
          {(rightText || RightIcon) && (
            <div className="text-right">
              <div className="flex items-center justify-end text-sm">
                {RightIcon && (
                  <RightIcon
                    className={`h-4 w-4 mr-1 ${rightIconColor || themeClasses.textSecondary}`}
                  />
                )}
                {rightText && (
                  <span className={themeClasses.textPrimary}>{rightText}</span>
                )}
              </div>
            </div>
          )}

          {/* Action Buttons */}
          {actions.map((action, index) => (
            <button
              key={index}
              type="button"
              onClick={action.onClick}
              disabled={action.disabled}
              className={getActionButtonClasses(action.variant)}
              title={action.label}
            >
              <action.icon className="h-4 w-4" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
});

export default UserListItem;
