/**
 * DynamicFeaturesEditor
 *
 * A dynamic component that loads features from the billing system API
 * and renders them as toggles/inputs for editing business permissions.
 *
 * This is the DYNAMIC version that gets features from the billing catalog,
 * which is the single source of truth. When you add a new feature to the
 * billing system, it automatically appears here.
 */

import React, { useMemo } from 'react';
import { Key, AlertCircle } from 'lucide-react';
import { useBillingFeatures, BillingFeature, FEATURE_CATEGORY_META } from '../../hooks/useBillingPlans';

export interface DynamicFeaturesEditorProps {
  /**
   * Current feature values mapped by tenant_field_name
   * For booleans: { can_use_sms_reminders: true, can_api_access: false, ... }
   * For integers: { max_users: 10, max_resources: 5, ... }
   */
  values: Record<string, boolean | number | null>;

  /**
   * Callback when a feature value changes
   * @param fieldName - The tenant_field_name of the feature
   * @param value - The new value (boolean for toggles, number for limits)
   */
  onChange: (fieldName: string, value: boolean | number | null) => void;

  /**
   * Optional: Only show features in these categories
   */
  categories?: BillingFeature['category'][];

  /**
   * Optional: Only show boolean or integer features
   */
  featureType?: 'boolean' | 'integer';

  /**
   * Optional: Exclude features by code
   */
  excludeCodes?: string[];

  /**
   * Show section header (default: true)
   */
  showHeader?: boolean;

  /**
   * Custom header title
   */
  headerTitle?: string;

  /**
   * Show descriptions under labels (default: false)
   */
  showDescriptions?: boolean;

  /**
   * Number of columns (default: 3)
   */
  columns?: 2 | 3 | 4;
}

const DynamicFeaturesEditor: React.FC<DynamicFeaturesEditorProps> = ({
  values,
  onChange,
  categories,
  featureType,
  excludeCodes = [],
  showHeader = true,
  headerTitle = 'Features & Permissions',
  showDescriptions = false,
  columns = 3,
}) => {
  const { data: features, isLoading, error } = useBillingFeatures();

  // Debug logging
  console.log('[DynamicFeaturesEditor] Features:', features?.length, 'Loading:', isLoading, 'Error:', error);

  // Filter and group features
  const groupedFeatures = useMemo(() => {
    if (!features) {
      console.log('[DynamicFeaturesEditor] No features data');
      return {};
    }

    // Filter features
    const filtered = features.filter(f => {
      if (excludeCodes.includes(f.code)) return false;
      if (categories && !categories.includes(f.category)) return false;
      if (featureType && f.feature_type !== featureType) return false;
      if (!f.is_overridable) return false;  // Skip non-overridable features
      if (!f.tenant_field_name) return false;  // Skip features without tenant field
      return true;
    });
    console.log('[DynamicFeaturesEditor] Filtered features:', filtered.length, 'featureType:', featureType);

    // Group by category
    const groups: Record<string, BillingFeature[]> = {};
    for (const feature of filtered) {
      if (!groups[feature.category]) {
        groups[feature.category] = [];
      }
      groups[feature.category].push(feature);
    }

    // Sort features within each category by display_order
    for (const category of Object.keys(groups)) {
      groups[category].sort((a, b) => a.display_order - b.display_order);
    }

    return groups;
  }, [features, categories, featureType, excludeCodes]);

  // Sort categories by their order
  const sortedCategories = useMemo(() => {
    return Object.keys(groupedFeatures).sort(
      (a, b) => (FEATURE_CATEGORY_META[a as BillingFeature['category']]?.order ?? 99) -
                (FEATURE_CATEGORY_META[b as BillingFeature['category']]?.order ?? 99)
    ) as BillingFeature['category'][];
  }, [groupedFeatures]);

  // Check if a dependent feature should be disabled
  const isDependencyDisabled = (feature: BillingFeature): boolean => {
    if (!feature.depends_on_code) return false;
    const parentFeature = features?.find(f => f.code === feature.depends_on_code);
    if (!parentFeature) return false;
    const parentValue = values[parentFeature.tenant_field_name];
    return !parentValue;
  };

  // Handle value change
  const handleChange = (feature: BillingFeature, newValue: boolean | number | null) => {
    onChange(feature.tenant_field_name, newValue);

    // If disabling a parent feature, also disable dependents
    if (feature.feature_type === 'boolean' && !newValue) {
      const dependents = features?.filter(f => f.depends_on_code === feature.code) ?? [];
      for (const dep of dependents) {
        if (values[dep.tenant_field_name]) {
          onChange(dep.tenant_field_name, false);
        }
      }
    }
  };

  const gridCols = {
    2: 'grid-cols-2',
    3: 'grid-cols-3',
    4: 'grid-cols-4',
  };

  if (isLoading) {
    return (
      <div className="space-y-4">
        {showHeader && (
          <h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
            <Key size={16} className="text-purple-500" />
            {headerTitle}
          </h3>
        )}
        <div className="animate-pulse space-y-3">
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24"></div>
          <div className="grid grid-cols-3 gap-3">
            {[1, 2, 3, 4, 5, 6].map(i => (
              <div key={i} className="h-12 bg-gray-100 dark:bg-gray-800 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-4">
        {showHeader && (
          <h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
            <Key size={16} className="text-purple-500" />
            {headerTitle}
          </h3>
        )}
        <div className="flex items-center gap-2 text-amber-600 dark:text-amber-400">
          <AlertCircle size={16} />
          <span className="text-sm">Failed to load features from billing system</span>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {showHeader && (
        <>
          <h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
            <Key size={16} className="text-purple-500" />
            {headerTitle}
          </h3>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            Control which features are available. Features are loaded from the billing system.
          </p>
        </>
      )}

      {sortedCategories.map(category => {
        const categoryFeatures = groupedFeatures[category];
        if (!categoryFeatures || categoryFeatures.length === 0) return null;

        const categoryMeta = FEATURE_CATEGORY_META[category];

        return (
          <div key={category}>
            <h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">
              {categoryMeta?.label || category}
            </h4>
            <div className={`grid ${gridCols[columns]} gap-3`}>
              {categoryFeatures.map(feature => {
                const isDisabled = isDependencyDisabled(feature);
                const currentValue = values[feature.tenant_field_name];

                if (feature.feature_type === 'boolean') {
                  const isChecked = currentValue === true;

                  return (
                    <label
                      key={feature.code}
                      className={`flex items-start gap-2 p-2 border border-gray-200 dark:border-gray-700 rounded-lg ${
                        isDisabled
                          ? 'opacity-50 cursor-not-allowed'
                          : 'hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer'
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={isChecked}
                        onChange={(e) => handleChange(feature, e.target.checked)}
                        disabled={isDisabled}
                        className="mt-0.5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 disabled:opacity-50"
                      />
                      <div className="flex-1 min-w-0">
                        <span className="text-sm text-gray-700 dark:text-gray-300 block">
                          {feature.name}
                        </span>
                        {showDescriptions && feature.description && (
                          <span className="text-xs text-gray-500 dark:text-gray-400 block mt-0.5">
                            {feature.description}
                          </span>
                        )}
                      </div>
                    </label>
                  );
                }

                // Integer feature (limit)
                const intValue = typeof currentValue === 'number' ? currentValue : 0;
                const isUnlimited = currentValue === null || currentValue === -1;

                return (
                  <div
                    key={feature.code}
                    className="p-2 border border-gray-200 dark:border-gray-700 rounded-lg"
                  >
                    <label className="text-sm text-gray-700 dark:text-gray-300 block mb-1">
                      {feature.name}
                    </label>
                    <div className="flex items-center gap-2">
                      <input
                        type="number"
                        min="-1"
                        value={isUnlimited ? -1 : intValue}
                        onChange={(e) => {
                          const val = parseInt(e.target.value);
                          handleChange(feature, val === -1 ? null : val);
                        }}
                        className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-1 focus:ring-indigo-500"
                      />
                    </div>
                    {showDescriptions && (
                      <span className="text-xs text-gray-500 dark:text-gray-400 block mt-1">
                        {feature.description} (-1 = unlimited)
                      </span>
                    )}
                  </div>
                );
              })}
            </div>

            {/* Show dependency hint for plugins category */}
            {category === 'plugins' && (
              (() => {
                const pluginsFeature = categoryFeatures.find(f => f.code === 'can_use_plugins');
                if (pluginsFeature && !values[pluginsFeature.tenant_field_name]) {
                  return (
                    <p className="text-xs text-amber-600 dark:text-amber-400 mt-2">
                      Enable "Use Plugins" to allow dependent features
                    </p>
                  );
                }
                return null;
              })()
            )}
          </div>
        );
      })}
    </div>
  );
};

export default DynamicFeaturesEditor;
