// File: src/components/UI/Form/FormSection.jsx

import React, { memo, useMemo } from "react";

/**
 * FormSection Component - Performance Optimized
 * Section container with title and description
 *
 * Performance optimizations:
 * - Component memoization with React.memo
 * - Memoized sub-elements to prevent re-renders
 * - Optimized className concatenation
 * - Children processing optimization
 * - Early return for empty sections
 *
 * @param {string} title - Section title
 * @param {string} description - Section description
 * @param {React.ReactNode} children - Section content
 * @param {string} className - Additional CSS classes
 */
const FormSection = memo(function FormSection({
  title,
  description,
  children,
  className = "",
}) {
  // Early return if completely empty section
  if (!title && !description && !children) {
    return null;
  }

  // Memoize container className
  const containerClassName = useMemo(() => {
    const baseClass = "mb-8";
    return className ? `${baseClass} ${className}` : baseClass;
  }, [className]);

  // Memoize title element
  const titleElement = useMemo(() => {
    if (!title) return null;

    return <h3 className="text-lg font-medium text-gray-900 mb-2">{title}</h3>;
  }, [title]);

  // Memoize description element
  const descriptionElement = useMemo(() => {
    if (!description) return null;

    return <p className="text-sm text-gray-600 mb-4">{description}</p>;
  }, [description]);

  // Memoize children wrapper with space-y-4 styling
  const childrenWrapper = useMemo(() => {
    if (!children) return null;

    // Process children to handle arrays and filter out null values
    let processedChildren = children;

    if (Array.isArray(children)) {
      // Use React.Children.toArray for proper key handling and filtering
      processedChildren = React.Children.toArray(children).filter(Boolean);

      // If no valid children after filtering, return null
      if (processedChildren.length === 0) {
        return null;
      }
    }

    return <div className="space-y-4">{processedChildren}</div>;
  }, [children]);

  return (
    <div className={containerClassName}>
      {titleElement}
      {descriptionElement}
      {childrenWrapper}
    </div>
  );
});

// Set display name for React DevTools
FormSection.displayName = "FormSection";

export default FormSection;
