import { useMemo } from 'react';
import { Action } from '../types/action';
import { Trigger } from '../types/trigger';

export interface TriggerAction {
  id: string;
  name: string;
  description: string;
  icon: string;
  category: string;
  integration?: string;
  isAvailable: boolean;
  availabilityReason: string;
  pluginType?: 'free' | 'paid' | '';
  installUrl?: string;
  isConnected: boolean;
  requiresConnection: boolean;
}

interface UseCategorizedItemsProps {
  type: 'trigger' | 'action';
  triggers: Trigger[];
  actions: Action[];
  searchQuery: string;
}

interface UseCategorizedItemsReturn {
  items: TriggerAction[];
  filteredItems: TriggerAction[];
  availableItems: TriggerAction[];
  notConnectedItems: TriggerAction[];
  gatedItems: TriggerAction[];
}

/**
 * Maps trigger type identifiers to appropriate Lucide icon names
 */
function getTriggerIcon(triggerType: string): string {
  if (triggerType.includes('user')) return 'UserPlus';
  if (triggerType.includes('post') || triggerType.includes('page')) return 'FileText';
  if (triggerType.includes('comment')) return 'MessageSquare';
  return 'Zap';
}

/**
 * Derives a display category for triggers based on type and label
 */
function deriveTriggerCategory(trigger: Trigger): string {
  const type = trigger.type.toLowerCase();
  const label = trigger.label.toLowerCase();

  if (type.includes('user') || label.includes('user')) return 'WordPress Users';
  if (
    type.includes('post') ||
    label.includes('post') ||
    type.includes('comment') ||
    label.includes('comment')
  )
    return 'WordPress Content';

  return 'General';
}

/**
 * Converts Trigger from API format to TriggerAction format
 */
function convertTriggerToTriggerAction(trigger: Trigger): TriggerAction {
  return {
    id: trigger.type,
    name: trigger.label,
    description: trigger.description,
    icon: getTriggerIcon(trigger.type),
    category: deriveTriggerCategory(trigger),
    integration: trigger.integration || 'wordpress',
    isAvailable: trigger.is_available ?? true,
    availabilityReason: trigger.availability_reason || '',
    pluginType: trigger.plugin_type || '',
    installUrl: trigger.install_url || '',
    isConnected: true, // Triggers don't require connections currently
    requiresConnection: false,
  };
}

/**
 * Maps action type identifiers to appropriate Lucide icon names
 */
function getActionIcon(actionType: string): string {
  if (actionType.includes('user')) return 'UserPlus';
  if (actionType.includes('post') || actionType.includes('page')) return 'FileText';
  if (actionType.includes('email') || actionType.includes('mail')) return 'Mail';
  if (actionType.includes('role')) return 'UserPlus';
  return 'Zap';
}

/**
 * Derives a display category for actions based on type and label
 */
function deriveActionCategory(action: Action): string {
  const type = action.type.toLowerCase();
  const label = action.label.toLowerCase();

  if (type.includes('user') || label.includes('user')) return 'WordPress Users';
  if (type.includes('post') || label.includes('post')) return 'WordPress Content';
  if (type.includes('email') || type.includes('mail')) return 'Email';

  return 'General';
}

/**
 * Converts Action from API format to TriggerAction format
 */
function convertActionToTriggerAction(action: Action): TriggerAction {
  return {
    id: action.type,
    name: action.label,
    description: action.description,
    icon: getActionIcon(action.type),
    category: deriveActionCategory(action),
    integration: action.integration || 'wordpress',
    isAvailable: action.is_available ?? true,
    availabilityReason: action.availability_reason || '',
    pluginType: action.plugin_type || '',
    installUrl: action.install_url || '',
    isConnected: action.is_connected ?? true,
    requiresConnection: action.requires_connection ?? false,
  };
}

/**
 * Hook for categorizing triggers/actions by availability status.
 * Separates items into: available & connected, needs connection, and gated.
 */
export function useCategorizedItems({
  type,
  triggers,
  actions,
  searchQuery,
}: UseCategorizedItemsProps): UseCategorizedItemsReturn {
  // Convert data to TriggerAction format based on type
  const items = useMemo<TriggerAction[]>(() => {
    if (type === 'trigger') {
      return triggers.map(convertTriggerToTriggerAction);
    }
    return actions.map(convertActionToTriggerAction);
  }, [type, triggers, actions]);

  // Filter items based on search (includes name, description, and integration)
  const filteredItems = useMemo(() => {
    const query = searchQuery.toLowerCase();
    return items.filter(
      (item) =>
        item.name.toLowerCase().includes(query) ||
        item.description.toLowerCase().includes(query) ||
        (item.integration?.toLowerCase().includes(query) ?? false),
    );
  }, [items, searchQuery]);

  // Separate into three groups
  const availableItems = useMemo(
    () =>
      filteredItems.filter(
        (item) => item.isAvailable && (!item.requiresConnection || item.isConnected),
      ),
    [filteredItems],
  );

  const notConnectedItems = useMemo(
    () =>
      filteredItems.filter(
        (item) => item.isAvailable && item.requiresConnection && !item.isConnected,
      ),
    [filteredItems],
  );

  const gatedItems = useMemo(
    () => filteredItems.filter((item) => !item.isAvailable),
    [filteredItems],
  );

  return {
    items,
    filteredItems,
    availableItems,
    notConnectedItems,
    gatedItems,
  };
}
