import React, { useMemo, useState } from 'react';
import { Pressable, Text, View } from 'react-native';
import {
  BookOpen,
  Brain,
  ChevronRight,
  Database,
  FileText,
  ListChecks,
  MessageSquare,
  Plug,
  ShieldCheck,
  Sparkles,
  Wrench,
  Zap,
  type LucideIcon,
} from 'lucide-react-native';

import { themedColor } from '../../theme';
import type { SuperagentToolRendererProps } from '../../types';
import {
  buildBlueprintBlocks,
  hasBlueprintContent,
  parseBlueprint,
  splitHeadline,
  type BlueprintBlock,
} from '../agentBlueprintUtils';
import { ExpandableSection } from '../primitives/ExpandableSection';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import { WidgetCard } from '../primitives/WidgetCard';
import { getSettledWidgetStatus } from '../toolWidgetUtils';

const BLOCK_ICONS: Record<string, LucideIcon> = {
  persona: Sparkles,
  operating_rules: ShieldCheck,
  data_model: Database,
  capabilities: Wrench,
  connectors: Plug,
  skills: BookOpen,
  automations: Zap,
  channels: MessageSquare,
  knowledge: FileText,
  memory: Brain,
};

/**
 * build_mode — native port of the web AgentBlueprint card: hero (name +
 * mission), capability pills that expand into a detail panel, and collapsed
 * build-sequence / coverage-notes sections. The web's "Build agent" / "Refine"
 * footer drives the chat composer through host-only APIs (chat-send bridge +
 * editor store) that aren't plumbed into native renderers, so the native card
 * is display-only — the user replies in chat to build or refine.
 */
export function AgentBlueprintWidget({ isLastAssistantMessage, toolCall }: SuperagentToolRendererProps) {
  const status = getSettledWidgetStatus(toolCall, isLastAssistantMessage);
  const args = useMemo(() => parseBlueprint(toolCall), [toolCall]);
  const blocks = useMemo(() => buildBlueprintBlocks(args), [args]);
  const [activeKey, setActiveKey] = useState<string | null>(null);

  if (status === 'running') {
    return <ToolWidgetRow icon={Sparkles} status="running" title="Designing your agent..." />;
  }
  if (status === 'error' || status === 'stopped') {
    return <ToolWidgetRow icon={Sparkles} status="error" title="Failed to design the agent" />;
  }
  if (!hasBlueprintContent(args, blocks)) {
    return (
      <ToolWidgetRow
        icon={Sparkles}
        note="ask me to summarize it"
        status="success"
        title="The blueprint couldn't be displayed in full"
      />
    );
  }

  const activeBlock = blocks.find((block) => block.key === activeKey) ?? null;
  const buildSequence = Array.isArray(args.build_sequence) ? args.build_sequence : [];

  return (
    <WidgetCard>
      <View style={toolWidgetStyles.cardBody}>
        <View style={[toolWidgetStyles.cardHeader, toolWidgetStyles.cardHeaderTop]}>
          <View style={toolWidgetStyles.cardIconBox}>
            <Sparkles color={themedColor('#A1A1AA')} size={15} strokeWidth={2.3} />
          </View>
          <View style={toolWidgetStyles.cardHeaderMeta}>
            <Text style={toolWidgetStyles.cardKicker}>Agent Blueprint</Text>
            <Text numberOfLines={1} style={toolWidgetStyles.cardTitle}>{args.agent_name || 'agent'}</Text>
            {args.mission ? (
              <Text numberOfLines={2} style={toolWidgetStyles.cardSubtitle}>{args.mission}</Text>
            ) : null}
          </View>
        </View>

        {blocks.length > 0 ? (
          <View style={toolWidgetStyles.pillRow}>
            {blocks.map((block) => (
              <BlockPill
                block={block}
                isActive={block.key === activeKey}
                key={block.key}
                onPress={() => setActiveKey((current) => (current === block.key ? null : block.key))}
              />
            ))}
          </View>
        ) : null}

        {activeBlock ? (
          <View style={toolWidgetStyles.panel}>
            {activeBlock.prose ? (
              <Text style={toolWidgetStyles.panelText}>{activeBlock.prose}</Text>
            ) : (
              activeBlock.items?.map((item, index) => <BlueprintItem key={index} text={item} />)
            )}
          </View>
        ) : null}

        {buildSequence.length > 0 || args.coverage_notes ? (
          <View style={toolWidgetStyles.cardDivider} />
        ) : null}
        {buildSequence.length > 0 ? (
          <ExpandableSection collapsedTitle={`Build sequence (${buildSequence.length})`}>
            <View style={toolWidgetStyles.panel}>
              {buildSequence.map((step, index) => (
                <Text key={index} style={toolWidgetStyles.panelText}>{`${index + 1}. ${step}`}</Text>
              ))}
            </View>
          </ExpandableSection>
        ) : null}
        {args.coverage_notes ? (
          <ExpandableSection collapsedTitle="Coverage notes">
            <View style={toolWidgetStyles.panel}>
              <Text style={toolWidgetStyles.panelText}>{args.coverage_notes}</Text>
            </View>
          </ExpandableSection>
        ) : null}
      </View>
    </WidgetCard>
  );
}

function BlockPill({
  block,
  isActive,
  onPress,
}: {
  block: BlueprintBlock;
  isActive: boolean;
  onPress: () => void;
}) {
  const Icon = BLOCK_ICONS[block.key] ?? Sparkles;
  return (
    <Pressable
      accessibilityRole="button"
      onPress={onPress}
      style={[toolWidgetStyles.pill, isActive ? toolWidgetStyles.pillActive : null]}
    >
      <Icon color={themedColor('#A1A1AA')} size={12} strokeWidth={2.3} />
      <Text style={toolWidgetStyles.pillText}>{block.label}</Text>
      {block.items ? <Text style={toolWidgetStyles.pillCount}>{block.items.length}</Text> : null}
    </Pressable>
  );
}

/**
 * One list item inside an expanded block: headline (title) always shown; the
 * long description collapses behind a chevron. Items without a "Title — desc"
 * split render as plain text.
 */
function BlueprintItem({ text }: { text: string }) {
  const [open, setOpen] = useState(false);
  const { title, description } = splitHeadline(text);

  if (!description) {
    return <Text style={toolWidgetStyles.panelText}>{title}</Text>;
  }

  return (
    <View>
      <Pressable accessibilityRole="button" onPress={() => setOpen((current) => !current)} style={toolWidgetStyles.panelItemHeader}>
        <ChevronRight
          color={themedColor('#8E8E93')}
          size={13}
          strokeWidth={2.3}
          style={open ? toolWidgetStyles.panelItemChevronOpen : toolWidgetStyles.panelItemChevron}
        />
        <Text style={toolWidgetStyles.panelItemTitle}>{title}</Text>
      </Pressable>
      {open ? <Text style={toolWidgetStyles.panelItemDescription}>{description}</Text> : null}
    </View>
  );
}
