// File: src/components/UIX/Tabs/Tabs.jsx
// Tabs Component - Performance Optimized

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

/**
 * Tabs Component - Performance Optimized
 * Enhanced tab navigation interface with responsive design and icon support
 *
 * @param {Array} tabs - Array of tab objects with id, label, icon (optional), to (optional), isActive (optional)
 * @param {string} activeTab - Active tab id (used when onTabChange is provided)
 * @param {function} onTabChange - Tab change handler for callback mode
 * @param {string} className - Additional CSS classes
 * @param {string} mode - 'callback' for onClick behavior, 'routing' for href navigation (default: 'callback')
 * @param {string} variant - 'default' for standard tabs, 'pills' for pill-style, 'underline' for simple underline (default: 'default')
 * @param {string} size - 'sm', 'md', 'lg' (default: 'md')
 * @param {boolean} fullWidth - Whether tabs should take full width (default: false)
 */

// Tab Item Component - Separated for performance
const TabItem = memo(
  function TabItem({ tab, index, isActive, mode, onTabChange, themeClasses, variant, size, fullWidth }) {
    // Memoize click handler
    const handleClick = useCallback(() => {
      // Use tab's own onClick if provided, otherwise use parent onTabChange
      if (tab.onClick) {
        tab.onClick();
      } else if (onTabChange && tab.id) {
        onTabChange(tab.id);
      }
    }, [tab, onTabChange]);

    // Size classes
    const sizeClasses = {
      sm: "py-2 px-3 text-sm",
      md: "py-3 px-4 text-sm sm:text-base",
      lg: "py-3 sm:py-4 px-1 text-base sm:text-lg",
    };

    // Memoize icon element
    const IconElement = useMemo(() => {
      if (!tab.icon) return null;
      const iconSize = size === "sm" ? "w-4 h-4" : size === "lg" ? "w-5 h-5" : "w-4 sm:w-5 h-4 sm:h-5";
      return <tab.icon className={`${iconSize} ml-1`} />;
    }, [tab.icon, size]);

    // Memoize classes based on active state and variant
    const tabClasses = useMemo(() => {
      const baseClasses = [
        "font-medium",
        "whitespace-nowrap",
        "inline-flex",
        "items-center",
        "justify-center",
        "transition-colors",
        "duration-200",
        sizeClasses[size] || sizeClasses.md,
      ];

      if (fullWidth) {
        baseClasses.push("flex-1");
      }

      // Variant-specific styling
      if (variant === "underline") {
        // Simple underline style - good for modals
        baseClasses.push("border-b-2");
        if (isActive) {
          baseClasses.push(themeClasses.textAccent, themeClasses.borderAccent);
        } else {
          baseClasses.push(
            "border-transparent",
            themeClasses.textSecondary,
            themeClasses.hoverTextPrimary
          );
        }
      } else if (variant === "pills") {
        // Pill-style tabs
        baseClasses.push("rounded-lg");
        if (isActive) {
          baseClasses.push(themeClasses.bgAccentLight, themeClasses.textAccent);
        } else {
          baseClasses.push(
            themeClasses.textSecondary,
            themeClasses.hoverBgMuted,
            themeClasses.hoverTextPrimary
          );
        }
      } else {
        // Default variant - original behavior
        baseClasses.push("border-b-4", "border-transparent");

        // Determine hover border color based on theme
        const hoverBorderClass = {
          red: "hover:border-red-500",
          blue: "hover:border-blue-500",
          purple: "hover:border-purple-500",
          green: "hover:border-green-500",
          charcoal: "hover:border-slate-500",
        }[themeClasses.currentTheme] || "hover:border-gray-500";

        if (isActive) {
          baseClasses.push(themeClasses.textPrimary);
        } else {
          baseClasses.push(
            themeClasses.textSecondary,
            themeClasses.hoverTextPrimary,
            hoverBorderClass
          );
        }
      }

      return baseClasses.filter(Boolean).join(" ");
    }, [isActive, themeClasses, variant, size, fullWidth]);

    // Routing mode with active state (non-interactive)
    if (mode === "routing" && isActive) {
      return (
        <div
          className={tabClasses}
          role="tab"
          aria-selected={true}
          aria-controls={`tabpanel-${tab.id || tab.label}`}
        >
          {tab.label}
          {IconElement}
        </div>
      );
    }

    // Routing mode with link
    if (mode === "routing" && tab.to) {
      return (
        <a
          href={tab.to}
          className={tabClasses}
          role="tab"
          aria-selected={false}
          aria-controls={`tabpanel-${tab.id || tab.label}`}
        >
          {tab.label}
          {IconElement}
        </a>
      );
    }

    // Callback mode with button
    return (
      <button
        onClick={handleClick}
        className={tabClasses}
        role="tab"
        aria-selected={isActive}
        aria-controls={`tabpanel-${tab.id}`}
        type="button"
      >
        {tab.label}
        {IconElement}
      </button>
    );
  },
  (prevProps, nextProps) => {
    // Custom comparison - only re-render when these props change
    return (
      prevProps.tab === nextProps.tab &&
      prevProps.index === nextProps.index &&
      prevProps.isActive === nextProps.isActive &&
      prevProps.mode === nextProps.mode &&
      prevProps.onTabChange === nextProps.onTabChange &&
      prevProps.themeClasses === nextProps.themeClasses &&
      prevProps.variant === nextProps.variant &&
      prevProps.size === nextProps.size &&
      prevProps.fullWidth === nextProps.fullWidth
    );
  },
);

TabItem.displayName = "TabItem";

// Main Tabs Component
const Tabs = memo(
  function Tabs({
    tabs = [],
    activeTab,
    onTabChange,
    className = "",
    mode = "callback",
    variant = "default",
    size = "md",
    fullWidth = false,
  }) {
    const { getThemeClasses, currentTheme } = useUIXTheme();

    // Memoize theme classes and current theme
    const themeClasses = useMemo(
      () => ({
        textPrimary: getThemeClasses("text-primary"),
        textSecondary: getThemeClasses("text-secondary"),
        textAccent: getThemeClasses("text-accent"),
        hoverTextPrimary: getThemeClasses("hover:text-primary"),
        bgAccentLight: getThemeClasses("bg-accent-light"),
        hoverBgMuted: getThemeClasses("hover:bg-muted"),
        borderAccent: getThemeClasses("border-accent"),
        borderSecondary: getThemeClasses("border-secondary"),
        currentTheme: currentTheme,
      }),
      [getThemeClasses, currentTheme],
    );

    // Memoize container classes
    const containerClasses = useMemo(() => {
      const classes = [];
      if (className) {
        classes.push(className);
      }
      return classes.join(" ");
    }, [className]);

    // Memoize nav classes based on variant
    const navClasses = useMemo(() => {
      if (variant === "underline") {
        return `border-b ${themeClasses.borderSecondary}`;
      } else if (variant === "pills") {
        return "";
      }
      return `px-4 sm:px-6 border-b border-gray-200 dark:border-gray-700`;
    }, [variant, themeClasses.borderSecondary]);

    // Memoize inner nav classes
    const innerNavClasses = useMemo(() => {
      const classes = ["flex", "overflow-x-auto", "scrollbar-hide"];
      if (variant === "underline") {
        // No margin adjustment needed for underline
      } else if (variant === "pills") {
        classes.push("space-x-2", "p-1");
      } else {
        classes.push("-mb-px", "space-x-4", "sm:space-x-8");
      }
      return classes.join(" ");
    }, [variant]);

    // Memoize tab items
    const TabItems = useMemo(() => {
      return tabs.map((tab, index) => {
        const isActive =
          mode === "routing" ? tab.isActive : activeTab === tab.id;

        return (
          <TabItem
            key={tab.id || index}
            tab={tab}
            index={index}
            isActive={isActive}
            mode={mode}
            onTabChange={onTabChange}
            themeClasses={themeClasses}
            variant={variant}
            size={size}
            fullWidth={fullWidth}
          />
        );
      });
    }, [tabs, mode, activeTab, onTabChange, themeClasses, variant, size, fullWidth]);

    return (
      <div className={containerClasses}>
        <div className={navClasses}>
          <nav
            className={innerNavClasses}
            aria-label="Tabs"
          >
            {TabItems}
          </nav>
        </div>
      </div>
    );
  },
  (prevProps, nextProps) => {
    // Custom comparison - only re-render when these props change
    // Note: Tabs can contain icon components, so use reference comparison
    return (
      prevProps.tabs === nextProps.tabs &&
      prevProps.tabs?.length === nextProps.tabs?.length &&
      prevProps.activeTab === nextProps.activeTab &&
      prevProps.onTabChange === nextProps.onTabChange &&
      prevProps.className === nextProps.className &&
      prevProps.mode === nextProps.mode &&
      prevProps.variant === nextProps.variant &&
      prevProps.size === nextProps.size &&
      prevProps.fullWidth === nextProps.fullWidth
    );
  },
);

Tabs.displayName = "Tabs";

export default Tabs;
