import React from 'react';
import { themedColor } from '../../theme';
import { Pressable, SafeAreaView, Text, View } from 'react-native';
import { ArrowRight } from 'lucide-react-native';

import { AgentSphereIcon } from '../branding/AgentSphereIcon';
import { styles } from '../../styles';
import { formatRelativeTime } from './timeUtils';
import type { SuperagentAgent, SuperagentHomeScreenViewProps, SuperagentMessage } from '../../types';

export function AgentCard({
  agent,
  latestMessages,
  currentUserAvatarUrl,
  onPress,
}: {
  agent: SuperagentAgent;
  // Accepted for call-site compatibility; no longer shown (meta pills removed).
  automationCount?: number;
  connectorCount?: number;
  latestMessages: SuperagentHomeScreenViewProps['latestMessages'];
  currentUserAvatarUrl?: string | null;
  onPress: () => void;
}) {
  const previewMessages = getPreviewMessages(latestMessages);
  const agentName = agent.name || 'Untitled Agent';
  const relativeTime = formatRelativeTime(agent.updatedAt);
  const activeText = relativeTime ? `Active ${relativeTime}` : 'Active recently';

  return (
    <View style={styles.heroPanel}>
      {/* Agent identity header */}
      <View style={styles.cardHeaderRow}>
        <View style={styles.cardAvatar}>
          <AgentSphereIcon agent={agent} size="header" />
        </View>
        <View style={styles.cardHeaderText}>
          <Text style={styles.agentName} numberOfLines={1}>{agentName}</Text>
          <Text style={styles.agentActiveTime} numberOfLines={1}>{activeText}</Text>
        </View>
      </View>

      {/* Message preview — last two messages as chat bubbles */}
      {previewMessages.length > 0 ? (
        <View style={styles.messagePanel}>
          {previewMessages.map((message, index) => (
            <MessageBubble
              key={message.id ?? index}
              message={message}
              agent={agent}
              agentName={agentName}
              currentUserAvatarUrl={currentUserAvatarUrl}
              isFirst={index === 0}
            />
          ))}
        </View>
      ) : null}

      {/* Continue button */}
      <Pressable
        accessibilityRole="button"
        onPress={onPress}
        style={({ pressed }) => [styles.continueButton, pressed && styles.pressed]}
      >
        <Text style={styles.continueButtonText} numberOfLines={1}>Continue with {agentName}</Text>
        <ArrowRight color={themedColor('#111111')} size={16} strokeWidth={2.5} />
      </Pressable>
    </View>
  );
}

function MessageBubble({
  message,
  agent,
  agentName,
  currentUserAvatarUrl,
  isFirst,
}: {
  message: SuperagentMessage;
  agent: SuperagentAgent;
  agentName: string;
  currentUserAvatarUrl?: string | null;
  isFirst: boolean;
}) {
  const isUser = message.role === 'user';

  return (
    <View style={isFirst ? undefined : styles.bubbleGroup}>
      {/* Label row */}
      <View style={[styles.bubbleLabelRow, isUser ? styles.rowEnd : styles.rowStart]}>
        {!isUser ? <AgentSphereIcon agent={agent} size="sm" /> : null}
        <Text style={[styles.bubbleLabel, isUser ? styles.bubbleLabelUser : styles.bubbleLabelAgent]}>
          {isUser ? 'You' : agentName}
        </Text>
        {isUser ? <AgentSphereIcon isUser size="sm" userAvatarUrl={currentUserAvatarUrl} /> : null}
      </View>
      {/* Bubble */}
      <View style={[styles.bubbleRow, isUser ? styles.rowEnd : styles.rowStart, isUser ? styles.bubbleRowUser : styles.bubbleRowAgent]}>
        <View style={[styles.bubble, isUser ? styles.userBubble : styles.assistantBubble]}>
          <Text style={styles.bubbleText} numberOfLines={3}>{message.content.trim()}</Text>
        </View>
      </View>
    </View>
  );
}

export function EmptyState({
  onCreateAgent,
  isCreating,
}: {
  onCreateAgent: () => void;
  isCreating: boolean;
}) {
  return (
    <View style={styles.emptyPanel}>
      <View style={styles.avatar}>
        <AgentSphereIcon size="header" />
      </View>
      <Text style={styles.emptyTitle}>Start with one task</Text>
      <Text style={styles.emptyBody}>
        Create a Superagent that can remember context, work with tools, and keep moving from your phone.
      </Text>
      <View style={styles.emptyChipRow}>
        {['Research', 'Sales', 'Support', 'Automations'].map((label) => (
          <View key={label} style={styles.emptyChip}>
            <Text style={styles.emptyChipText}>{label}</Text>
          </View>
        ))}
      </View>
      <Pressable
        accessibilityRole="button"
        disabled={isCreating}
        onPress={onCreateAgent}
        style={({ pressed }) => [styles.primaryButton, pressed && styles.pressed]}
      >
        <Text style={styles.primaryButtonText}>{isCreating ? 'Creating...' : 'Create Superagent'}</Text>
      </Pressable>
    </View>
  );
}

export function RecentAgentCard({
  agent,
  onPress,
}: {
  agent: SuperagentAgent;
  onPress: () => void;
}) {
  const relativeTime = formatRelativeTime(agent.updatedAt);
  const updatedText = relativeTime ? `Updated ${relativeTime}` : 'Updated recently';

  return (
    <Pressable
      accessibilityRole="button"
      onPress={onPress}
      style={({ pressed }) => [styles.recentCard, pressed && styles.pressed]}
    >
      <View style={styles.compactAvatar}>
        <AgentSphereIcon agent={agent} size="header" />
      </View>
      <View style={styles.recentCardBody}>
        <Text style={styles.recentCardName} numberOfLines={1}>{agent.name || 'Untitled Agent'}</Text>
        <Text style={styles.recentCardTime} numberOfLines={1}>{updatedText}</Text>
      </View>
    </Pressable>
  );
}

export function HeaderProfile({ userAvatarUrl }: { userAvatarUrl?: string | null }) {
  return (
    <View style={styles.headerAvatar}>
      <AgentSphereIcon isUser size="md" userAvatarUrl={userAvatarUrl} />
    </View>
  );
}

export function CreateAgentButton({
  isCreating,
  onPress,
}: {
  isCreating: boolean;
  onPress: () => void;
}) {
  return (
    <View style={styles.createRow}>
      <Text style={styles.orText}>Or</Text>
      <Pressable
        accessibilityRole="button"
        disabled={isCreating}
        onPress={onPress}
        style={({ pressed }) => pressed && styles.pressed}
      >
        <Text style={styles.createLinkText}>{isCreating ? 'Creating…' : 'Create a new superagent'}</Text>
      </Pressable>
    </View>
  );
}

export function PlaceholderPage({
  title,
  body,
  onBack,
}: {
  title: string;
  body: string;
  onBack: () => void;
}) {
  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.placeholder}>
        <Pressable accessibilityRole="button" onPress={onBack} style={styles.backButton}>
          <Text style={styles.backButtonText}>Back</Text>
        </Pressable>
        <Text style={styles.title}>{title}</Text>
        <Text style={styles.subtitle}>{body}</Text>
      </View>
    </SafeAreaView>
  );
}

// Last two user/assistant messages with content, oldest-first — matches the
// web hero, which shows the tail of the conversation as chat bubbles.
function getPreviewMessages(messages: SuperagentHomeScreenViewProps['latestMessages']): SuperagentMessage[] {
  if (!messages?.length) return [];

  return messages
    .filter((message) => (message.role === 'user' || message.role === 'assistant') && message.content?.trim())
    .slice(-2);
}
