import React from 'react';
import { Pressable, ScrollView, Text, View } from 'react-native';
import { Plus } from 'lucide-react-native';

import { AgentSphereIcon } from '../branding/AgentSphereIcon';
import { styles } from '../../styles';
import { themedColor } from '../../theme';
import { formatChatTimestamp } from './timeUtils';
import type { SuperagentFolder, SuperagentMessage, SuperagentAgent } from '../../types';

export type ChatFilter = { id: string; name: string };

export function FolderChips({
  filters,
  selectedId,
  onSelect,
}: {
  filters: ChatFilter[];
  selectedId: string;
  onSelect: (id: string) => void;
}) {
  return (
    <View style={styles.chipsBar}>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.chipsContent}
      >
        {filters.map((filter) => {
          const selected = filter.id === selectedId;
          return (
            <Pressable
              key={filter.id}
              accessibilityRole="button"
              accessibilityState={{ selected }}
              onPress={() => onSelect(filter.id)}
              style={({ pressed }) => [
                styles.folderChip,
                selected ? styles.folderChipSelected : styles.folderChipUnselected,
                pressed && styles.cardPressed,
              ]}
            >
              <Text style={[styles.folderChipText, selected && styles.folderChipTextSelected]}>
                {filter.name}
              </Text>
            </Pressable>
          );
        })}
      </ScrollView>
    </View>
  );
}

export function ChatConversationRow({
  agent,
  messages,
  onPress,
  onLongPress,
}: {
  agent: SuperagentAgent;
  messages?: SuperagentMessage[];
  onPress: () => void;
  onLongPress?: () => void;
}) {
  const snippet = getChatPreview(messages, agent.description);
  const timestamp = formatChatTimestamp(agent.updatedAt);

  return (
    <Pressable
      accessibilityRole="button"
      onPress={onPress}
      onLongPress={onLongPress}
      delayLongPress={300}
      style={({ pressed }) => [styles.convRow, pressed && styles.convRowPressed]}
    >
      <View style={styles.convAvatar}>
        <AgentSphereIcon agent={agent} size={44} />
      </View>
      <View style={styles.convBody}>
        <View style={styles.convTopLine}>
          <Text style={styles.convName} numberOfLines={1}>{agent.name || 'Untitled Agent'}</Text>
          {timestamp ? <Text style={styles.convTime}>{timestamp}</Text> : null}
        </View>
        <Text style={styles.convSnippet} numberOfLines={2}>{snippet}</Text>
      </View>
    </Pressable>
  );
}

export function CreateAgentRow({
  isCreating,
  subtitle,
  onPress,
}: {
  isCreating: boolean;
  subtitle: string;
  onPress: () => void;
}) {
  return (
    <Pressable
      accessibilityRole="button"
      accessibilityLabel="Create new agent"
      disabled={isCreating}
      onPress={onPress}
      style={({ pressed }) => [styles.createAgentRow, pressed && styles.convRowPressed]}
    >
      <View style={styles.createAgentRowIcon}>
        <Plus color={themedColor('#F7F7F7')} size={20} strokeWidth={2.6} />
      </View>
      <View style={styles.createAgentRowBody}>
        <Text style={styles.createAgentRowTitle}>{isCreating ? 'Creating…' : 'Create new agent'}</Text>
        <Text style={styles.createAgentRowSubtitle}>{subtitle}</Text>
      </View>
    </Pressable>
  );
}

/** Build the chip filters: an "All" chip followed by every folder. */
export function buildChatFilters(folders: SuperagentFolder[]): ChatFilter[] {
  return [{ id: 'all', name: 'All' }, ...folders.map((folder) => ({ id: folder.id, name: folder.name }))];
}

// Inbox snippet of the latest message, with a "You:" prefix for the user's own
// turn — markdown stripped so it reads as plain text across two lines.
function getChatPreview(messages: SuperagentMessage[] | undefined, fallback?: string): string {
  const last = getLastContentMessage(messages);
  if (!last) return fallback?.trim() || 'Tap to start chatting';

  const body = stripMarkdown(last.content);
  return last.role === 'user' ? `You: ${body}` : body;
}

function stripMarkdown(text: string): string {
  return text
    .replace(/```[\s\S]*?```/g, ' ')          // fenced code blocks
    .replace(/`([^`]+)`/g, '$1')              // inline code
    .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')    // images
    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')  // links -> link text
    .replace(/^\s{0,3}#{1,6}\s+/gm, '')       // headings
    .replace(/^\s*[-*+]\s+/gm, '')            // list bullets
    .replace(/[*_~]/g, '')                    // emphasis markers
    .replace(/\s*\n+\s*/g, ' ')               // newlines -> spaces
    .replace(/\s{2,}/g, ' ')                  // collapse whitespace runs
    .trim();
}

function getLastContentMessage(messages?: SuperagentMessage[]): SuperagentMessage | null {
  if (!messages?.length) return null;
  for (let index = messages.length - 1; index >= 0; index -= 1) {
    const message = messages[index];
    if ((message.role === 'user' || message.role === 'assistant') && message.content?.trim()) {
      return message;
    }
  }
  return null;
}
