import React from 'react';
import { SilkeBox } from '../silke-box';
import { SilkeText } from '../silke-text';
import { SilkeColor } from '../../silke-theme-provider';
import { VevConditionSuggestion } from './types';
import { VevCondition } from '@vev/interactions';
import { VevProps } from '@vev/utils';
import { isWidgetOption } from './utils';

export type SilkeConditionsTagProps = {
  condition: VevCondition[0];
  variables: any[];
  systemOptions?: VevConditionSuggestion[];
  widgetOptions?: VevProps[];
};

export function SilkeConditionsTag(props: SilkeConditionsTagProps) {
  const { condition, variables, systemOptions } = props;

  const getTagDisplayText = (label: string | number | boolean) => {
    if (typeof label === 'boolean') {
      return label.toString();
    }

    if (typeof label === 'number') {
      return label.toString();
    }

    // Check for system
    if (typeof label === 'string' && label.startsWith('vev/')) {
      const match = systemOptions?.find((v) => v.value === label);
      return match ? match.label : label;
    }

    // Check for variables
    if (typeof label === 'string' && label.startsWith('{{')) {
      const match = variables?.find((v) => v.key === label.replace('{{', '').replace('}}', ''));
      return match ? match.name : label;
    }

    // Check for AND/OR
    if (typeof label === 'string' && (label === 'AND' || label === 'OR')) {
      return label.toLowerCase();
    }

    return label;
  };

  const getTagColor = (label: string | number | boolean): SilkeColor => {
    if (typeof label === 'number') {
      return 'neutral-60';
    }

    // Check for system
    if (typeof label === 'string' && label.startsWith('{{')) {
      return 'success-30';
    }

    // Check for variables
    if (typeof label === 'string' && label.startsWith('vev/')) {
      return 'support-tertiary-40';
    }

    // Check for widgetOptions
    const match = isWidgetOption(label, props.widgetOptions);
    if (match) {
      return 'success-30';
    }

    return 'neutral-100';
  };

  return (
    <SilkeBox align="center">
      <SilkeText size="small" color={getTagColor(condition)}>
        {getTagDisplayText(condition)}
      </SilkeText>
    </SilkeBox>
  );
}
