// File: src/components/UI/CheckboxGroup/CheckboxGroup.jsx

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

/**
 * CheckboxGroup Component - Performance Optimized
 * Group of checkbox options with consistent styling
 */
const CheckboxGroup = memo(
  ({
    label,
    description,
    required = false,
    error,
    options = [],
    value = {},
    onChange,
    disabled = false,
    className = "",
    size = "md",
  }) => {
    // Memoize size classes to prevent recreation
    const sizeClasses = useMemo(
      () => ({
        label: {
          sm: "text-sm",
          md: "text-base sm:text-lg",
          lg: "text-lg sm:text-xl",
        }[size],
        checkbox: {
          sm: "w-4 h-4",
          md: "w-5 h-5",
          lg: "w-6 h-6",
        }[size],
        padding: {
          sm: "p-3",
          md: "p-4",
          lg: "p-5",
        }[size],
        text: {
          sm: "text-sm",
          md: "text-base",
          lg: "text-base",
        }[size],
        description: {
          sm: "text-xs",
          md: "text-sm",
          lg: "text-sm",
        }[size],
      }),
      [size],
    );

    // Memoize the change handler
    const handleChange = useCallback(
      (optionKey) => {
        if (disabled || !onChange) return;

        const newValue = {
          ...value,
          [optionKey]: !value[optionKey],
        };
        onChange(newValue);
      },
      [disabled, onChange, value],
    );

    // Memoize label classes
    const labelClasses = useMemo(() => {
      return `block ${sizeClasses.label} font-semibold text-gray-700 mb-3 flex items-center`;
    }, [sizeClasses.label]);

    // Memoize checkbox input classes
    const checkboxInputClasses = useMemo(() => {
      return `mt-1 ${sizeClasses.checkbox} text-red-600 bg-gray-100 border-gray-300 rounded focus:ring-red-500 transition-colors duration-200`;
    }, [sizeClasses.checkbox]);

    // Memoize the error icon component
    const ErrorIcon = useMemo(() => {
      if (!error) return null;

      return (
        <p className="mb-3 text-sm text-red-600 flex items-center">
          <svg
            className="w-4 h-4 mr-1"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 14.5c-.77.833.192 2.5 1.732 2.5z"
            />
          </svg>
          {error}
        </p>
      );
    }, [error]);

    // Memoize the label component
    const LabelComponent = useMemo(() => {
      if (!label) return null;

      return (
        <label className={labelClasses}>
          {label}
          {required && <span className="text-red-500 ml-1">*</span>}
        </label>
      );
    }, [label, required, labelClasses]);

    // Memoize the description component
    const DescriptionComponent = useMemo(() => {
      if (!description) return null;

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

    // Memoize option rendering function
    const renderOption = useCallback(
      (option) => {
        const isChecked = !!value[option.key];

        // Build container classes
        const containerClasses = [
          "flex",
          "items-start",
          sizeClasses.padding,
          "rounded-xl",
          "border-2",
          "cursor-pointer",
          "transition-all",
          "duration-200",
        ];

        if (isChecked) {
          containerClasses.push("bg-red-50", "border-red-500", "shadow-md");
        } else {
          containerClasses.push(
            "bg-white",
            "border-gray-200",
            "hover:border-gray-300",
            "hover:shadow-sm",
          );
        }

        if (disabled) {
          containerClasses.push("opacity-50", "cursor-not-allowed");
        }

        return (
          <label key={option.key} className={containerClasses.join(" ")}>
            <input
              type="checkbox"
              checked={isChecked}
              onChange={() => handleChange(option.key)}
              disabled={disabled}
              className={checkboxInputClasses}
              aria-checked={isChecked}
              aria-disabled={disabled}
              aria-describedby={
                option.description ? `${option.key}-description` : undefined
              }
            />
            <div className="ml-4">
              <div className="flex items-center">
                {option.icon && (
                  <option.icon
                    className={`${sizeClasses.checkbox} mr-2 text-red-500`}
                  />
                )}
                <span
                  className={`${sizeClasses.text} font-medium text-gray-900`}
                >
                  {option.label}
                </span>
              </div>
              {option.description && (
                <p
                  id={`${option.key}-description`}
                  className={`${sizeClasses.description} text-gray-500 mt-1`}
                >
                  {option.description}
                </p>
              )}
            </div>
          </label>
        );
      },
      [value, handleChange, disabled, sizeClasses, checkboxInputClasses],
    );

    // Memoize the options list
    const OptionsList = useMemo(() => {
      if (!options || options.length === 0) {
        return null;
      }

      return <div className="space-y-4">{options.map(renderOption)}</div>;
    }, [options, renderOption]);

    return (
      <div className={className}>
        {LabelComponent}
        {DescriptionComponent}
        {ErrorIcon}
        {OptionsList}
      </div>
    );
  },
  (prevProps, nextProps) => {
    // Custom comparison for memo optimization
    // Only re-render when these specific props change
    return (
      prevProps.label === nextProps.label &&
      prevProps.description === nextProps.description &&
      prevProps.required === nextProps.required &&
      prevProps.error === nextProps.error &&
      prevProps.disabled === nextProps.disabled &&
      prevProps.className === nextProps.className &&
      prevProps.size === nextProps.size &&
      prevProps.onChange === nextProps.onChange &&
      // Reference comparison for options (may contain complex data)
      prevProps.options === nextProps.options &&
      prevProps.options?.length === nextProps.options?.length &&
      // Reference comparison for value
      prevProps.value === nextProps.value
    );
  },
);

// Display name for debugging
CheckboxGroup.displayName = "CheckboxGroup";

export default CheckboxGroup;
