import React, { useMemo } from 'react';
import { Text, View } from 'react-native';
import { Bot, Clock, Database, Plug, Zap, type LucideIcon } from 'lucide-react-native';

import { useConversationFeatureNavigation } from '../../featureNavigationContext';
import { themedColor } from '../../theme';
import type { SuperagentToolRendererProps } from '../../types';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { WidgetCard } from '../primitives/WidgetCard';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import { getSettledWidgetStatus, getStringArg, parseToolArgs } from '../toolWidgetUtils';
import {
  describeWorkflowTrigger,
  getWorkflowBadgeStatus,
  getWorkflowName,
  getWorkflowTriggerConfig,
  type WorkflowTriggerType,
} from '../workflowWidgetUtils';
import { ActiveBadge, AutomationCardFooter } from './automationCardParts';

const TRIGGER_ICONS: Record<WorkflowTriggerType, LucideIcon> = {
  scheduled: Clock,
  entity: Database,
  connector: Plug,
  in_app_agent: Bot,
};

/**
 * create_or_update_workflow — native port of the web CreateWorkflowWidget task
 * card (agent-builder variant): name + Active/Inactive badge, trigger summary,
 * description, and the shared "runs when triggered" / credits footer. Tapping it
 * opens the Automations settings modal (workflows and automations share that
 * tab), mirroring the automation card.
 */
export function CreateWorkflowWidget({ agent, isLastAssistantMessage, toolCall }: SuperagentToolRendererProps) {
  const openFeature = useConversationFeatureNavigation();
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const status = getSettledWidgetStatus(toolCall, isLastAssistantMessage);

  if (status === 'running') {
    return (
      <ToolWidgetRow chipText={getStringArg(args, ['name']) || null} icon={Zap} status="running" title="Saving workflow..." />
    );
  }
  if (status === 'error' || status === 'stopped') {
    return <ToolWidgetRow icon={Zap} status="error" title="Failed to save workflow" />;
  }

  const trigger = getWorkflowTriggerConfig(args);
  const triggerLabel = trigger ? describeWorkflowTrigger(trigger.type, trigger.config) : null;
  const TriggerIcon = trigger ? TRIGGER_ICONS[trigger.type] : Zap;
  const description = getStringArg(args, ['description']);
  const badgeStatus = getWorkflowBadgeStatus(args, toolCall.results);

  return (
    <WidgetCard
      accessibilityLabel="Open Automations settings"
      onPress={openFeature ? () => openFeature('automations') : undefined}
    >
      <View style={toolWidgetStyles.cardBody}>
        <View style={toolWidgetStyles.cardHeader}>
          <View style={toolWidgetStyles.cardIconBox}>
            <TriggerIcon color={themedColor('#A1A1AA')} size={15} strokeWidth={2.3} />
          </View>
          <View style={toolWidgetStyles.cardHeaderMeta}>
            <View style={toolWidgetStyles.cardTitleRow}>
              <Text numberOfLines={1} style={toolWidgetStyles.cardTitle}>{getWorkflowName(args)}</Text>
              {badgeStatus ? <ActiveBadge inactiveLabel="Inactive" isActive={badgeStatus === 'active'} /> : null}
            </View>
            {triggerLabel ? <Text style={toolWidgetStyles.cardSubtitle}>{triggerLabel}</Text> : null}
          </View>
        </View>

        {description ? (
          <Text numberOfLines={3} style={toolWidgetStyles.cardDescription}>{description}</Text>
        ) : null}

        <AutomationCardFooter agentName={agent.name} />
      </View>
    </WidgetCard>
  );
}
