v0.1 public beta early access on GitHub
Home / Screens / chat-chat-thread
Screen template

Chat Thread Screen

One-on-one chat with grouped bubbles, photo messages, day separators, tapback reactions, check-mark read receipts, animated typing indicator, and a pill composer

pro Expo Go ✓ iosandroid gestures: tap · scroll haptics: light · medium
$ npx lumioui add chat-chat-thread
import { ChatThreadScreen } from "@/screens/chat/chat-thread";
Native packages installed6
@lumioui/ui@latest@lumioui/core@latestreact-native-safe-area-context@*react-native-reanimated@*react-native-svg@*nativewind@*
chat/chat-thread.tsxsource · yours to edit
import * as React from "react";
import { useRef, useState } from "react";
import { View, FlatList } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
  Easing,
  useSharedValue,
  useAnimatedStyle,
  withDelay,
  withRepeat,
  withTiming,
} from "react-native-reanimated";
import { Avatar, Button, Glass, Icon, Image, Input, KeyboardAvoiding, Text } from "@lumioui/ui";
import { cn, ease, timing, useHaptic, useReducedMotion, } from "@lumioui/core";
import { Press } from "../shared";

export interface ChatMessage {
  id: string;
  senderId: string;
  /** Text body — omit for a pure image message. */
  text?: string;
  /** Photo message — renders as a media bubble instead of text. */
  imageUrl?: string;
  time: string;
  /** Whether to show a timestamp above this bubble. */
  showTimestamp?: boolean;
  /** Day separator chip rendered above the group ("Today", "Yesterday"). */
  dateLabel?: string;
  /** Delivery receipt on your own messages (iMessage's "Delivered"/"Read"). */
  status?: "sent" | "delivered" | "read";
  /** Tapback-style reaction pill pinned to the bubble's outer top corner. */
  reaction?: string;
}

export interface ChatPeer {
  id: string;
  name: string;
  avatarUrl?: string;
  online?: boolean;
  /** Custom presence line ("Active 5m ago", "In a meeting"). */
  statusText?: string;
}

export interface ChatThreadScreenProps {
  messages?: ChatMessage[];
  currentUserId?: string;
  peer?: ChatPeer;
  /** Show a "typing…" indicator bubble from the peer. */
  peerTyping?: boolean;
  onSend?: (text: string) => void;
  onBack?: () => void;
  /** Attach affordance on the left of the composer. */
  onAttach?: () => void;
  /** Header trailing actions. */
  onCall?: () => void;
  onMore?: () => void;
  /** Tapping the peer's name/avatar (opens their profile). */
  onPeerPress?: () => void;
  /** Prefilled composer text for demos/previews — production hosts omit it. */
  defaultDraft?: string;
}

const DEFAULT_PEER: ChatPeer = {
  id: "peer-1",
  name: "Maya Chen",
  online: true,
  avatarUrl: "https://i.pravatar.cc/150?img=47",
};

const DEFAULT_MESSAGES: ChatMessage[] = [
  { id: "m1", senderId: "peer-1", text: "Hey! The new settings screens are up in Figma", time: "6:42 PM", dateLabel: "Yesterday", showTimestamp: true },
  { id: "m2", senderId: "peer-1", text: "Dashboard got approved this morning btw", time: "6:42 PM" },
  { id: "m3", senderId: "me", text: "Nice — I'll do a spacing pass tonight", time: "6:44 PM", status: "read" },
  { id: "m4", senderId: "peer-1", text: "The icon grid still feels cramped on small screens", time: "6:45 PM" },
  { id: "m5", senderId: "me", text: "On it — bumping section spacing and tightening the rails", time: "6:47 PM", status: "read" },
  { id: "m6", senderId: "peer-1", imageUrl: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=640&h=480&fit=crop&q=70&auto=format", time: "9:04 AM", dateLabel: "Today", showTimestamp: true, reaction: "❤️" },
  { id: "m7", senderId: "peer-1", text: "Sunrise from the ridge this morning — worth the 5am alarm", time: "9:04 AM" },
  { id: "m8", senderId: "me", text: "Unfair. I'm at a desk", time: "9:07 AM", status: "read" },
  { id: "m9", senderId: "me", text: "Pushed the spacing fix too — take a look", time: "9:07 AM", status: "read" },
];

const RECEIPT_LABEL = { sent: "Sent", delivered: "Delivered", read: "Read" } as const;

/** Staggered mount — bubbles rise and fade in sequence. Choreography data
 *  (like EmptyState's 90ms cadence), capped so lazily-mounted rows never
 *  wait on a deep index. */
const MOUNT_STAGGER = 40;
const MOUNT_MAX_DELAY = 280;
const MOUNT_TIMING = { duration: timing.normal.duration, easing: Easing.bezier(...ease.out) };

/** Fade + small rise on mount, delayed by index. Reduced motion: fade only. */
function MountIn({
  index,
  className,
  children,
}: {
  index: number;
  className?: string;
  children: React.ReactNode;
}) {
  const reduce = useReducedMotion();
  const t = useSharedValue(reduce ? 1 : 0);
  React.useEffect(() => {
    if (reduce) {
      t.value = 1;
      return;
    }
    t.value = withDelay(
      Math.min(index * MOUNT_STAGGER, MOUNT_MAX_DELAY),
      withTiming(1, MOUNT_TIMING)
    );
  }, [index, reduce, t]);
  const style = useAnimatedStyle(() => ({
    opacity: t.value,
    transform: [{ translateY: (1 - t.value) * 8 }],
  }));
  return (
    <Animated.View style={style} className={className}>
      {children}
    </Animated.View>
  );
}

/** Bubble content shared by both sides — a photo message renders the media
 *  itself (no color wash behind it); a text message sits on the bubble's
 *  painted surface. */
function BubbleContent({
  message,
  sender,
  textClassName,
}: {
  message: ChatMessage;
  sender: string;
  textClassName: string;
}) {
  return message.imageUrl ? (
    <Image
      source={{ uri: message.imageUrl }}
      rounded="none"
      aspectRatio={4 / 3}
      className="w-56"
      accessibilityLabel={`Photo from ${sender}`}
    />
  ) : (
    <Text className={textClassName}>{message.text}</Text>
  );
}
BubbleContent.displayName = "BubbleContent";

interface BubbleProps {
  message: ChatMessage;
  sender: string;
  /** Last bubble of a same-sender run — carries the "tail" corner. */
  tail: boolean;
}

// NOTE: @lumioui/pro has a six-treatment message-bubble, but the screens
// package may only depend on @lumioui/ui + @lumioui/core — so the two
// bubble treatments used here (peer/muted, own/primary) live in-file.

/** Tapback pill — iMessage hangs the reaction off the bubble's outer top
 *  corner (away from the avatar column), on a raised card chip. */
function ReactionPill({ reaction, side }: { reaction: string; side: "left" | "right" }) {
  return (
    <View
      className={cn(
        "absolute -top-2.5 overflow-hidden rounded-full px-1.5 py-0.5",
        side === "right" ? "-right-2" : "-left-2"
      )}
      accessibilityLabel={reaction === "\u2764\uFE0F" ? "Loved" : reaction}
      accessibilityRole="text"
    >
      <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
      <Icon name="heart" size="sm" color="destructive" filled />
    </View>
  );
}
ReactionPill.displayName = "ReactionPill";

/** Peer bubble — muted surface, tail on the bottom-left. */
function MessageBubble({ message, sender, tail }: BubbleProps) {
  const media = !!message.imageUrl;
  return (
    <View className="max-w-[75%] self-start">
      <View
        accessible
        accessibilityRole={media ? "image" : "text"}
        accessibilityLabel={`${sender}, ${message.time}: ${media ? "photo" : message.text}`}
        className={cn(
          "overflow-hidden rounded-2xl",
          !media && "px-4 py-2.5",
          tail && "rounded-bl-md"
        )}
      >
        {!media ? (
          <Glass interactive effect="clear" sheen={0.45} className="absolute inset-0 rounded-2xl" pointerEvents="none" />
        ) : null}
        <BubbleContent message={message} sender={sender} textClassName="text-foreground" />
      </View>
      {message.reaction ? <ReactionPill reaction={message.reaction} side="right" /> : null}
    </View>
  );
}
MessageBubble.displayName = "MessageBubble";

/** Own bubble — primary surface, right-aligned, tail on the bottom-right. */
function OwnBubble({ message, sender, tail }: BubbleProps) {
  const media = !!message.imageUrl;
  return (
    <View className="ml-auto max-w-[75%] self-end">
      <View
        accessible
        accessibilityRole={media ? "image" : "text"}
        accessibilityLabel={`${sender}, ${message.time}: ${media ? "photo" : message.text}`}
        className={cn(
          "rounded-2xl",
          media ? "overflow-hidden" : "bg-[#1B1B26] px-4 py-2.5",
          tail && "rounded-br-md"
        )}
      >
        <BubbleContent
          message={message}
          sender={sender}
          textClassName="text-white"
        />
      </View>
      {message.reaction ? <ReactionPill reaction={message.reaction} side="left" /> : null}
    </View>
  );
}
OwnBubble.displayName = "OwnBubble";

/** WhatsApp receipt ticks — one check while "sent", a grey pair when
 *  "delivered", and the pair flips to accent once "read". */
function ReceiptTicks({ status }: { status: "sent" | "delivered" | "read" }) {
  const color = status === "read" ? "#3E9AA3" : "mutedForeground";
  return (
    <View className="flex-row items-center" accessible={false}>
      <Icon name="check" size="sm" color={color} />
      {status !== "sent" ? (
        <Icon name="check" size="sm" color={color} className="-ml-2.5" />
      ) : null}
    </View>
  );
}
ReceiptTicks.displayName = "ReceiptTicks";

/** One pulsing dot of the typing indicator — staggered start keeps the
 *  three dots on a travelling wave instead of blinking in unison. */
function TypingDot({ delay, dim }: { delay: number; dim: boolean }) {
  const v = useSharedValue(0.3);
  React.useEffect(() => {
    if (dim) {
      v.value = 0.5;
      return;
    }
    // Ambient loop, not a UI transition — a calm fixed period reads better
    // than the sub-300ms interaction tokens.
    v.value = withDelay(delay, withRepeat(withTiming(1, { duration: 550 }), -1, true));
  }, [v, delay, dim]);
  const style = useAnimatedStyle(() => ({
    opacity: 0.35 + v.value * 0.65,
    transform: [{ translateY: (1 - v.value) * 1.5 - 1.5 }],
  }));
  return (
    <Animated.View
      style={style}
      className="h-1.5 w-1.5 rounded-full bg-muted-foreground"
    />
  );
}

/** Chat thread — grouped bubbles with sender avatars, receipts, animated
 *  typing indicator, and an attach + send composer pinned to the keyboard. */
export function ChatThreadScreen({
  messages = DEFAULT_MESSAGES,
  currentUserId = "me",
  peer = DEFAULT_PEER,
  peerTyping = true,
  onSend,
  onBack,
  onAttach,
  onCall,
  onMore,
  onPeerPress,
  defaultDraft,
}: ChatThreadScreenProps) {
  const haptics = useHaptic();
  const insets = useSafeAreaInsets();
  const reduceMotion = useReducedMotion();
  const [draft, setDraft] = useState(defaultDraft ?? "");
  const [headerH, setHeaderH] = useState(0);
  const [composerH, setComposerH] = useState(0);
  const listRef = useRef<FlatList<ChatMessage>>(null);

  const send = () => {
    const text = draft.trim();
    if (!text) return;
    // No manual haptic — the send Button fires haptic="medium" itself.
    onSend?.(text);
    setDraft("");
  };

  const presence = peer.statusText ?? (peer.online ? "Active now" : "Offline");

  return (
    <SafeAreaView className="flex-1 bg-[#F4F5F9] dark:bg-[#111114]" edges={["top"]}>
      {/* Header — iOS 26 floating chrome: back disc, identity capsule,
          call + overflow discs. Messages scroll under individual floats. */}
      <View
        pointerEvents="box-none"
        onLayout={(e) => setHeaderH(e.nativeEvent.layout.height)}
        className="absolute inset-x-4 top-0 z-10 flex-row items-center gap-2"
        style={{ top: insets.top + 8 }}
      >
        {onBack ? (
          <Press
            onPress={() => {
              haptics.light();
              onBack();
            }}
            accessibilityRole="button"
            accessibilityLabel="Go back"
            hitSlop={12}
            className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
          >
            <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
            <Icon name="chevron-left" size="md" color="foreground" />
          </Press>
        ) : null}
        <Press
          onPress={
            onPeerPress
              ? () => {
                  haptics.light();
                  onPeerPress();
                }
              : undefined
          }
          accessibilityRole={onPeerPress ? "button" : undefined}
          accessibilityLabel={`${peer.name}, ${presence}`}
          disabled={!onPeerPress}
          className="h-11 flex-1 flex-row items-center gap-2.5 overflow-hidden rounded-full pl-1.5 pr-4"
        >
          <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
          <Avatar
            size="sm"
            source={peer.avatarUrl ? { uri: peer.avatarUrl } : undefined}
            fallback={peer.name}
            status={peer.online ? "online" : undefined}
            alt={`${peer.name}'s avatar`}
          />
          <View>
            <Text variant="small" accessibilityRole="header">
              {peer.name}
            </Text>
            <Text variant="muted" className="text-xs">
              {presence}
            </Text>
          </View>
        </Press>
        <Press
          onPress={() => {
            haptics.light();
            onCall?.();
          }}
          accessibilityRole="button"
          accessibilityLabel={`Call ${peer.name}`}
          hitSlop={8}
          className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
        >
          <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
          <Icon name="phone" size="md" color="foreground" />
        </Press>
        <Press
          onPress={() => {
            haptics.light();
            onMore?.();
          }}
          accessibilityRole="button"
          accessibilityLabel="Conversation options"
          hitSlop={8}
          className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
        >
          <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
          <Icon name="more-vertical" size="md" color="foreground" />
        </Press>
      </View>

      {/* Pinned message — Telegram/WhatsApp pin bar under the header. */}
      <Press
        onPress={() => haptics.light()}
        accessibilityRole="button"
        accessibilityLabel="Pinned message: spacing tokens are merged"
        className="mx-4 mb-2 mt-2 flex-row items-center gap-2.5 overflow-hidden rounded-xl px-3 py-2"
        style={{ marginTop: headerH + 8 }}
      >
        <Glass interactive effect="clear" sheen={0.5} className="absolute inset-0 rounded-xl" pointerEvents="none" />
        <View className="h-8 w-0.5 rounded-full bg-[#BEF04C]" />
        <View className="flex-1">
          <Text variant="small" className="text-xs font-semibold">
            Pinned message
          </Text>
          <Text variant="muted" className="text-xs" numberOfLines={1}>
            Spacing tokens are merged — rebase before you continue
          </Text>
        </View>
        <Icon name="pin" size="sm" color="mutedForeground" />
      </Press>

      <KeyboardAvoiding className="flex-1">
        {/* Messages */}
        <FlatList
          ref={listRef}
          data={messages}
          keyExtractor={(item) => item.id}
          className="flex-1"
          contentContainerClassName="px-4 pb-6 pt-4"
          contentContainerStyle={{
            paddingTop: 8,
            paddingBottom: composerH + 12,
          }}
          showsVerticalScrollIndicator={false}
          onContentSizeChange={() => listRef.current?.scrollToEnd({ animated: false })}
          renderItem={({ item, index }) => {
            const mine = item.senderId === currentUserId;
            const sender = mine ? "You" : peer.name;
            // iOS grouping: consecutive same-sender bubbles sit tight and
            // only the LAST bubble of a run carries the "tail" corner.
            // A timestamp header always opens a fresh group.
            const prevMsg = messages[index - 1];
            const nextMsg = messages[index + 1];
            // A date chip or timestamp header always opens a fresh group.
            const isFirstOfRun =
              !prevMsg ||
              prevMsg.senderId !== item.senderId ||
              !!item.showTimestamp ||
              !!item.dateLabel;
            const isLastOfRun =
              !nextMsg ||
              nextMsg.senderId !== item.senderId ||
              !!nextMsg.showTimestamp ||
              !!nextMsg.dateLabel;
            return (
              <MountIn
                index={index}
                className={cn(index > 0 && (isFirstOfRun ? "mt-2" : "mt-0.5"))}
              >
                {item.dateLabel ? (
                  // iMessage day separator — a tonal pill, not a bare label.
                  <View className="items-center pb-1 pt-3">
                    <View className="overflow-hidden rounded-full px-3 py-1">
                      <Glass interactive effect="clear" sheen={0.4} className="absolute inset-0 rounded-full" pointerEvents="none" />
                      <Text
                        variant="muted"
                        className="text-xs font-semibold"
                        accessibilityRole="header"
                      >
                        {item.dateLabel}
                      </Text>
                    </View>
                  </View>
                ) : null}
                {item.showTimestamp ? (
                  <Text variant="muted" className="py-2 text-center text-xs tabular-nums">
                    {item.time}
                  </Text>
                ) : null}
                <View className="flex-row items-center gap-2">
                  {/* Their runs get a fixed avatar column — the avatar shows
                      on the first bubble of the group and the empty slot
                      keeps later bubbles aligned. */}
                  {!mine ? (
                    <View className="w-6 items-center self-start">
                      {isFirstOfRun ? (
                        <Avatar
                          size="sm"
                          className="h-6 w-6"
                          source={peer.avatarUrl ? { uri: peer.avatarUrl } : undefined}
                          fallback={peer.name}
                          alt=""
                        />
                      ) : null}
                    </View>
                  ) : null}
                  {mine ? (
                    <OwnBubble message={item} sender={sender} tail={isLastOfRun} />
                  ) : (
                    <MessageBubble message={item} sender={sender} tail={isLastOfRun} />
                  )}
                </View>
                {/* Delivery receipt — ticks + timestamp hang off the last
                    own bubble of a run, right-aligned under the tail. */}
                {mine && item.status && isLastOfRun ? (
                  <View
                    className="mt-0.5 flex-row items-center gap-1 self-end"
                    accessibilityLabel={`Message ${RECEIPT_LABEL[item.status].toLowerCase()} at ${item.time}`}
                  >
                    <ReceiptTicks status={item.status} />
                    <Text variant="muted" className="text-xs tabular-nums">
                      {RECEIPT_LABEL[item.status]} {item.time}
                    </Text>
                  </View>
                ) : null}
              </MountIn>
            );
          }}
          ListFooterComponent={
            peerTyping ? (
              <View className="mt-2 flex-row items-center gap-2">
                <View className="w-6 items-center">
                  <Avatar
                    size="sm"
                    className="h-6 w-6"
                    source={peer.avatarUrl ? { uri: peer.avatarUrl } : undefined}
                    fallback={peer.name}
                    alt=""
                  />
                </View>
                <View
                  className="self-start overflow-hidden rounded-2xl rounded-bl-md px-4 py-3.5"
                  accessible
                  accessibilityRole="text"
                  accessibilityLabel={`${peer.name} is typing`}
                >
                  <Glass interactive effect="clear" sheen={0.45} className="absolute inset-0 rounded-2xl" pointerEvents="none" />
                  <View className="flex-row items-center gap-1" accessible={false}>
                    <TypingDot delay={0} dim={reduceMotion} />
                    <TypingDot delay={140} dim={reduceMotion} />
                    <TypingDot delay={280} dim={reduceMotion} />
                  </View>
                </View>
              </View>
            ) : null
          }
        />

        {/* Composer — attach disc, growing field, send armed only with text.
            Individual floats over the stream — no band, iOS 26 idiom. */}
        <View
          pointerEvents="box-none"
          onLayout={(e) => setComposerH(e.nativeEvent.layout.height)}
          className="absolute inset-x-0 bottom-0 flex-row items-end gap-2 px-3 pt-3"
          style={{ paddingBottom: insets.bottom + 4 }}
        >
          <Button
            variant="glass"
            size="icon"
            haptic="light"
            onPress={onAttach}
            accessibilityLabel="Add attachment"
          >
            <Icon name="plus" size="md" color="secondaryForeground" />
          </Button>
          <View className="flex-1">
            <Input
              placeholder="Message…"
              value={draft}
              onChangeText={setDraft}
              onSubmitEditing={send}
              returnKeyType="send"
              // iMessage composer idiom — a pill field with dictation at rest.
              className="rounded-full"
              glass
              rightIcon={
                <Icon name="mic" size="sm" color="mutedForeground" />
              }
              accessibilityLabel="Message input"
            />
          </View>
          <Button
            size="icon"
            className="bg-[#1B1B26]"
            haptic="medium"
            disabled={draft.trim().length === 0}
            onPress={send}
            accessibilityLabel="Send message"
            accessibilityState={{ disabled: draft.trim().length === 0 }}
          >
            {/* iMessage idiom — an up-arrow in a filled circle, not a plane. */}
            <Icon name="arrow-up" size="sm" color="#FFFFFF" />
          </Button>
        </View>
      </KeyboardAvoiding>
    </SafeAreaView>
  );
}
agent prompt — paste into Claude Code, Cursor, Devin…
Recreate the "Chat Thread Screen" screen in React Native using LumioUI.

Goal: One-on-one chat with grouped bubbles, photo messages, day separators, tapback reactions, check-mark read receipts, animated typing indicator, and a pill composer Match the reference implementation's layout, behavior, and motion exactly — this is a production screen, not a mockup.

## Setup

Fastest path — install the screen plus its component deps:

```bash
npx lumioui add chat-chat-thread
```

Or pull just the components: `npx lumioui add avatar button icon image input keyboard-avoiding text`

Native packages:
- @lumioui/ui@latest
- @lumioui/core@latest
- react-native-safe-area-context@*
- react-native-reanimated@*
- react-native-svg@*
- nativewind@*

Stack assumptions: Expo SDK 54 / RN 0.81, Reanimated 4, NativeWind v4, TypeScript strict, Expo Go compatible.

## Components — how, where, when

### `avatar` — Circular user image with fallback initials and status dot.
- `<Avatar>` ×3

### `button` — Tactile pill button with press spring, ink wash and async loading.
- `<Button>` ×2

### `icon` — Lucide icon set mapped to theme colors and sizes.
- `<Icon>` ×10

### `image` — Cached image with placeholder, fallback and aspect handling.
- `<Image>` ×1

### `input` — Labeled field with focus ring, error shake and success check.
- `<Input>` ×1

### `keyboard-avoiding` — View that lifts above the keyboard on both platforms.
- `<KeyboardAvoiding>` ×1

### `text` — Themed type scale from caption to display.
- `<Text>` ×8

## Conventions (non-negotiable)

- Styling via NativeWind `className` with semantic tokens only: `bg-background`, `text-foreground`, `bg-card`, `text-card-foreground`, `bg-secondary`, `bg-muted`, `text-muted-foreground`, `bg-accent`, `bg-destructive`, `border-border`. Hard-coded colors only inside media overlays (`text-white`, `bg-black/N`).
- Motion via the token presets from `@lumioui/core` (`spring.press`, `spring.surface`, `spring.glide`, `timing.fast`, `timing.slow`, …) — no bespoke spring configs or durations.
- Gate transform motion behind `useReducedMotion()`; keep opacity/color feedback, drop travel and overshoot.
- Haptics via `useHaptic()`: `light` on press, `selection` on toggle/select, `warning` on invalid input. Never import expo-haptics directly.
- Press feedback via `usePressAnimation()` (~0.97 scale), not `activeOpacity` tricks.
- a11y: `accessibilityRole` + `accessibilityLabel` on every control, touch targets ≥44pt.
- Entrance choreography: staggered `Mount` wrappers (delay 0/60/120…) so regions land in sequence instead of popping in at once.
- Wrap the screen in `SafeAreaView`; keep dark mode working via the semantic tokens.

## Deliverable

One file: `screens/chat/chat-thread.tsx` exporting ChatThreadScreen. Preserve the props interface — the host app wires the callbacks (navigation, submit handlers) through them.

## Reference implementation

The LumioUI source for this screen — reproduce it faithfully:

```tsx
import * as React from "react";
import { useRef, useState } from "react";
import { View, FlatList } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, {
  Easing,
  useSharedValue,
  useAnimatedStyle,
  withDelay,
  withRepeat,
  withTiming,
} from "react-native-reanimated";
import { Avatar, Button, Glass, Icon, Image, Input, KeyboardAvoiding, Text } from "@lumioui/ui";
import { cn, ease, timing, useHaptic, useReducedMotion, } from "@lumioui/core";
import { Press } from "../shared";

export interface ChatMessage {
  id: string;
  senderId: string;
  /** Text body — omit for a pure image message. */
  text?: string;
  /** Photo message — renders as a media bubble instead of text. */
  imageUrl?: string;
  time: string;
  /** Whether to show a timestamp above this bubble. */
  showTimestamp?: boolean;
  /** Day separator chip rendered above the group ("Today", "Yesterday"). */
  dateLabel?: string;
  /** Delivery receipt on your own messages (iMessage's "Delivered"/"Read"). */
  status?: "sent" | "delivered" | "read";
  /** Tapback-style reaction pill pinned to the bubble's outer top corner. */
  reaction?: string;
}

export interface ChatPeer {
  id: string;
  name: string;
  avatarUrl?: string;
  online?: boolean;
  /** Custom presence line ("Active 5m ago", "In a meeting"). */
  statusText?: string;
}

export interface ChatThreadScreenProps {
  messages?: ChatMessage[];
  currentUserId?: string;
  peer?: ChatPeer;
  /** Show a "typing…" indicator bubble from the peer. */
  peerTyping?: boolean;
  onSend?: (text: string) => void;
  onBack?: () => void;
  /** Attach affordance on the left of the composer. */
  onAttach?: () => void;
  /** Header trailing actions. */
  onCall?: () => void;
  onMore?: () => void;
  /** Tapping the peer's name/avatar (opens their profile). */
  onPeerPress?: () => void;
  /** Prefilled composer text for demos/previews — production hosts omit it. */
  defaultDraft?: string;
}

const DEFAULT_PEER: ChatPeer = {
  id: "peer-1",
  name: "Maya Chen",
  online: true,
  avatarUrl: "https://i.pravatar.cc/150?img=47",
};

const DEFAULT_MESSAGES: ChatMessage[] = [
  { id: "m1", senderId: "peer-1", text: "Hey! The new settings screens are up in Figma", time: "6:42 PM", dateLabel: "Yesterday", showTimestamp: true },
  { id: "m2", senderId: "peer-1", text: "Dashboard got approved this morning btw", time: "6:42 PM" },
  { id: "m3", senderId: "me", text: "Nice — I'll do a spacing pass tonight", time: "6:44 PM", status: "read" },
  { id: "m4", senderId: "peer-1", text: "The icon grid still feels cramped on small screens", time: "6:45 PM" },
  { id: "m5", senderId: "me", text: "On it — bumping section spacing and tightening the rails", time: "6:47 PM", status: "read" },
  { id: "m6", senderId: "peer-1", imageUrl: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=640&h=480&fit=crop&q=70&auto=format", time: "9:04 AM", dateLabel: "Today", showTimestamp: true, reaction: "❤️" },
  { id: "m7", senderId: "peer-1", text: "Sunrise from the ridge this morning — worth the 5am alarm", time: "9:04 AM" },
  { id: "m8", senderId: "me", text: "Unfair. I'm at a desk", time: "9:07 AM", status: "read" },
  { id: "m9", senderId: "me", text: "Pushed the spacing fix too — take a look", time: "9:07 AM", status: "read" },
];

const RECEIPT_LABEL = { sent: "Sent", delivered: "Delivered", read: "Read" } as const;

/** Staggered mount — bubbles rise and fade in sequence. Choreography data
 *  (like EmptyState's 90ms cadence), capped so lazily-mounted rows never
 *  wait on a deep index. */
const MOUNT_STAGGER = 40;
const MOUNT_MAX_DELAY = 280;
const MOUNT_TIMING = { duration: timing.normal.duration, easing: Easing.bezier(...ease.out) };

/** Fade + small rise on mount, delayed by index. Reduced motion: fade only. */
function MountIn({
  index,
  className,
  children,
}: {
  index: number;
  className?: string;
  children: React.ReactNode;
}) {
  const reduce = useReducedMotion();
  const t = useSharedValue(reduce ? 1 : 0);
  React.useEffect(() => {
    if (reduce) {
      t.value = 1;
      return;
    }
    t.value = withDelay(
      Math.min(index * MOUNT_STAGGER, MOUNT_MAX_DELAY),
      withTiming(1, MOUNT_TIMING)
    );
  }, [index, reduce, t]);
  const style = useAnimatedStyle(() => ({
    opacity: t.value,
    transform: [{ translateY: (1 - t.value) * 8 }],
  }));
  return (
    <Animated.View style={style} className={className}>
      {children}
    </Animated.View>
  );
}

/** Bubble content shared by both sides — a photo message renders the media
 *  itself (no color wash behind it); a text message sits on the bubble's
 *  painted surface. */
function BubbleContent({
  message,
  sender,
  textClassName,
}: {
  message: ChatMessage;
  sender: string;
  textClassName: string;
}) {
  return message.imageUrl ? (
    <Image
      source={{ uri: message.imageUrl }}
      rounded="none"
      aspectRatio={4 / 3}
      className="w-56"
      accessibilityLabel={`Photo from ${sender}`}
    />
  ) : (
    <Text className={textClassName}>{message.text}</Text>
  );
}
BubbleContent.displayName = "BubbleContent";

interface BubbleProps {
  message: ChatMessage;
  sender: string;
  /** Last bubble of a same-sender run — carries the "tail" corner. */
  tail: boolean;
}

// NOTE: @lumioui/pro has a six-treatment message-bubble, but the screens
// package may only depend on @lumioui/ui + @lumioui/core — so the two
// bubble treatments used here (peer/muted, own/primary) live in-file.

/** Tapback pill — iMessage hangs the reaction off the bubble's outer top
 *  corner (away from the avatar column), on a raised card chip. */
function ReactionPill({ reaction, side }: { reaction: string; side: "left" | "right" }) {
  return (
    <View
      className={cn(
        "absolute -top-2.5 overflow-hidden rounded-full px-1.5 py-0.5",
        side === "right" ? "-right-2" : "-left-2"
      )}
      accessibilityLabel={reaction === "\u2764\uFE0F" ? "Loved" : reaction}
      accessibilityRole="text"
    >
      <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
      <Icon name="heart" size="sm" color="destructive" filled />
    </View>
  );
}
ReactionPill.displayName = "ReactionPill";

/** Peer bubble — muted surface, tail on the bottom-left. */
function MessageBubble({ message, sender, tail }: BubbleProps) {
  const media = !!message.imageUrl;
  return (
    <View className="max-w-[75%] self-start">
      <View
        accessible
        accessibilityRole={media ? "image" : "text"}
        accessibilityLabel={`${sender}, ${message.time}: ${media ? "photo" : message.text}`}
        className={cn(
          "overflow-hidden rounded-2xl",
          !media && "px-4 py-2.5",
          tail && "rounded-bl-md"
        )}
      >
        {!media ? (
          <Glass interactive effect="clear" sheen={0.45} className="absolute inset-0 rounded-2xl" pointerEvents="none" />
        ) : null}
        <BubbleContent message={message} sender={sender} textClassName="text-foreground" />
      </View>
      {message.reaction ? <ReactionPill reaction={message.reaction} side="right" /> : null}
    </View>
  );
}
MessageBubble.displayName = "MessageBubble";

/** Own bubble — primary surface, right-aligned, tail on the bottom-right. */
function OwnBubble({ message, sender, tail }: BubbleProps) {
  const media = !!message.imageUrl;
  return (
    <View className="ml-auto max-w-[75%] self-end">
      <View
        accessible
        accessibilityRole={media ? "image" : "text"}
        accessibilityLabel={`${sender}, ${message.time}: ${media ? "photo" : message.text}`}
        className={cn(
          "rounded-2xl",
          media ? "overflow-hidden" : "bg-[#1B1B26] px-4 py-2.5",
          tail && "rounded-br-md"
        )}
      >
        <BubbleContent
          message={message}
          sender={sender}
          textClassName="text-white"
        />
      </View>
      {message.reaction ? <ReactionPill reaction={message.reaction} side="left" /> : null}
    </View>
  );
}
OwnBubble.displayName = "OwnBubble";

/** WhatsApp receipt ticks — one check while "sent", a grey pair when
 *  "delivered", and the pair flips to accent once "read". */
function ReceiptTicks({ status }: { status: "sent" | "delivered" | "read" }) {
  const color = status === "read" ? "#3E9AA3" : "mutedForeground";
  return (
    <View className="flex-row items-center" accessible={false}>
      <Icon name="check" size="sm" color={color} />
      {status !== "sent" ? (
        <Icon name="check" size="sm" color={color} className="-ml-2.5" />
      ) : null}
    </View>
  );
}
ReceiptTicks.displayName = "ReceiptTicks";

/** One pulsing dot of the typing indicator — staggered start keeps the
 *  three dots on a travelling wave instead of blinking in unison. */
function TypingDot({ delay, dim }: { delay: number; dim: boolean }) {
  const v = useSharedValue(0.3);
  React.useEffect(() => {
    if (dim) {
      v.value = 0.5;
      return;
    }
    // Ambient loop, not a UI transition — a calm fixed period reads better
    // than the sub-300ms interaction tokens.
    v.value = withDelay(delay, withRepeat(withTiming(1, { duration: 550 }), -1, true));
  }, [v, delay, dim]);
  const style = useAnimatedStyle(() => ({
    opacity: 0.35 + v.value * 0.65,
    transform: [{ translateY: (1 - v.value) * 1.5 - 1.5 }],
  }));
  return (
    <Animated.View
      style={style}
      className="h-1.5 w-1.5 rounded-full bg-muted-foreground"
    />
  );
}

/** Chat thread — grouped bubbles with sender avatars, receipts, animated
 *  typing indicator, and an attach + send composer pinned to the keyboard. */
export function ChatThreadScreen({
  messages = DEFAULT_MESSAGES,
  currentUserId = "me",
  peer = DEFAULT_PEER,
  peerTyping = true,
  onSend,
  onBack,
  onAttach,
  onCall,
  onMore,
  onPeerPress,
  defaultDraft,
}: ChatThreadScreenProps) {
  const haptics = useHaptic();
  const insets = useSafeAreaInsets();
  const reduceMotion = useReducedMotion();
  const [draft, setDraft] = useState(defaultDraft ?? "");
  const [headerH, setHeaderH] = useState(0);
  const [composerH, setComposerH] = useState(0);
  const listRef = useRef<FlatList<ChatMessage>>(null);

  const send = () => {
    const text = draft.trim();
    if (!text) return;
    // No manual haptic — the send Button fires haptic="medium" itself.
    onSend?.(text);
    setDraft("");
  };

  const presence = peer.statusText ?? (peer.online ? "Active now" : "Offline");

  return (
    <SafeAreaView className="flex-1 bg-[#F4F5F9] dark:bg-[#111114]" edges={["top"]}>
      {/* Header — iOS 26 floating chrome: back disc, identity capsule,
          call + overflow discs. Messages scroll under individual floats. */}
      <View
        pointerEvents="box-none"
        onLayout={(e) => setHeaderH(e.nativeEvent.layout.height)}
        className="absolute inset-x-4 top-0 z-10 flex-row items-center gap-2"
        style={{ top: insets.top + 8 }}
      >
        {onBack ? (
          <Press
            onPress={() => {
              haptics.light();
              onBack();
            }}
            accessibilityRole="button"
            accessibilityLabel="Go back"
            hitSlop={12}
            className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
          >
            <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
            <Icon name="chevron-left" size="md" color="foreground" />
          </Press>
        ) : null}
        <Press
          onPress={
            onPeerPress
              ? () => {
                  haptics.light();
                  onPeerPress();
                }
              : undefined
          }
          accessibilityRole={onPeerPress ? "button" : undefined}
          accessibilityLabel={`${peer.name}, ${presence}`}
          disabled={!onPeerPress}
          className="h-11 flex-1 flex-row items-center gap-2.5 overflow-hidden rounded-full pl-1.5 pr-4"
        >
          <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
          <Avatar
            size="sm"
            source={peer.avatarUrl ? { uri: peer.avatarUrl } : undefined}
            fallback={peer.name}
            status={peer.online ? "online" : undefined}
            alt={`${peer.name}'s avatar`}
          />
          <View>
            <Text variant="small" accessibilityRole="header">
              {peer.name}
            </Text>
            <Text variant="muted" className="text-xs">
              {presence}
            </Text>
          </View>
        </Press>
        <Press
          onPress={() => {
            haptics.light();
            onCall?.();
          }}
          accessibilityRole="button"
          accessibilityLabel={`Call ${peer.name}`}
          hitSlop={8}
          className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
        >
          <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
          <Icon name="phone" size="md" color="foreground" />
        </Press>
        <Press
          onPress={() => {
            haptics.light();
            onMore?.();
          }}
          accessibilityRole="button"
          accessibilityLabel="Conversation options"
          hitSlop={8}
          className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
        >
          <Glass interactive effect="regular" sheen={0.5} className="absolute inset-0 rounded-full" pointerEvents="none" />
          <Icon name="more-vertical" size="md" color="foreground" />
        </Press>
      </View>

      {/* Pinned message — Telegram/WhatsApp pin bar under the header. */}
      <Press
        onPress={() => haptics.light()}
        accessibilityRole="button"
        accessibilityLabel="Pinned message: spacing tokens are merged"
        className="mx-4 mb-2 mt-2 flex-row items-center gap-2.5 overflow-hidden rounded-xl px-3 py-2"
        style={{ marginTop: headerH + 8 }}
      >
        <Glass interactive effect="clear" sheen={0.5} className="absolute inset-0 rounded-xl" pointerEvents="none" />
        <View className="h-8 w-0.5 rounded-full bg-[#BEF04C]" />
        <View className="flex-1">
          <Text variant="small" className="text-xs font-semibold">
            Pinned message
          </Text>
          <Text variant="muted" className="text-xs" numberOfLines={1}>
            Spacing tokens are merged — rebase before you continue
          </Text>
        </View>
        <Icon name="pin" size="sm" color="mutedForeground" />
      </Press>

      <KeyboardAvoiding className="flex-1">
        {/* Messages */}
        <FlatList
          ref={listRef}
          data={messages}
          keyExtractor={(item) => item.id}
          className="flex-1"
          contentContainerClassName="px-4 pb-6 pt-4"
          contentContainerStyle={{
            paddingTop: 8,
            paddingBottom: composerH + 12,
          }}
          showsVerticalScrollIndicator={false}
          onContentSizeChange={() => listRef.current?.scrollToEnd({ animated: false })}
          renderItem={({ item, index }) => {
            const mine = item.senderId === currentUserId;
            const sender = mine ? "You" : peer.name;
            // iOS grouping: consecutive same-sender bubbles sit tight and
            // only the LAST bubble of a run carries the "tail" corner.
            // A timestamp header always opens a fresh group.
            const prevMsg = messages[index - 1];
            const nextMsg = messages[index + 1];
            // A date chip or timestamp header always opens a fresh group.
            const isFirstOfRun =
              !prevMsg ||
              prevMsg.senderId !== item.senderId ||
              !!item.showTimestamp ||
              !!item.dateLabel;
            const isLastOfRun =
              !nextMsg ||
              nextMsg.senderId !== item.senderId ||
              !!nextMsg.showTimestamp ||
              !!nextMsg.dateLabel;
            return (
              <MountIn
                index={index}
                className={cn(index > 0 && (isFirstOfRun ? "mt-2" : "mt-0.5"))}
              >
                {item.dateLabel ? (
                  // iMessage day separator — a tonal pill, not a bare label.
                  <View className="items-center pb-1 pt-3">
                    <View className="overflow-hidden rounded-full px-3 py-1">
                      <Glass interactive effect="clear" sheen={0.4} className="absolute inset-0 rounded-full" pointerEvents="none" />
                      <Text
                        variant="muted"
                        className="text-xs font-semibold"
                        accessibilityRole="header"
                      >
                        {item.dateLabel}
                      </Text>
                    </View>
                  </View>
                ) : null}
                {item.showTimestamp ? (
                  <Text variant="muted" className="py-2 text-center text-xs tabular-nums">
                    {item.time}
                  </Text>
                ) : null}
                <View className="flex-row items-center gap-2">
                  {/* Their runs get a fixed avatar column — the avatar shows
                      on the first bubble of the group and the empty slot
                      keeps later bubbles aligned. */}
                  {!mine ? (
                    <View className="w-6 items-center self-start">
                      {isFirstOfRun ? (
                        <Avatar
                          size="sm"
                          className="h-6 w-6"
                          source={peer.avatarUrl ? { uri: peer.avatarUrl } : undefined}
                          fallback={peer.name}
                          alt=""
                        />
                      ) : null}
                    </View>
                  ) : null}
                  {mine ? (
                    <OwnBubble message={item} sender={sender} tail={isLastOfRun} />
                  ) : (
                    <MessageBubble message={item} sender={sender} tail={isLastOfRun} />
                  )}
                </View>
                {/* Delivery receipt — ticks + timestamp hang off the last
                    own bubble of a run, right-aligned under the tail. */}
                {mine && item.status && isLastOfRun ? (
                  <View
                    className="mt-0.5 flex-row items-center gap-1 self-end"
                    accessibilityLabel={`Message ${RECEIPT_LABEL[item.status].toLowerCase()} at ${item.time}`}
                  >
                    <ReceiptTicks status={item.status} />
                    <Text variant="muted" className="text-xs tabular-nums">
                      {RECEIPT_LABEL[item.status]} {item.time}
                    </Text>
                  </View>
                ) : null}
              </MountIn>
            );
          }}
          ListFooterComponent={
            peerTyping ? (
              <View className="mt-2 flex-row items-center gap-2">
                <View className="w-6 items-center">
                  <Avatar
                    size="sm"
                    className="h-6 w-6"
                    source={peer.avatarUrl ? { uri: peer.avatarUrl } : undefined}
                    fallback={peer.name}
                    alt=""
                  />
                </View>
                <View
                  className="self-start overflow-hidden rounded-2xl rounded-bl-md px-4 py-3.5"
                  accessible
                  accessibilityRole="text"
                  accessibilityLabel={`${peer.name} is typing`}
                >
                  <Glass interactive effect="clear" sheen={0.45} className="absolute inset-0 rounded-2xl" pointerEvents="none" />
                  <View className="flex-row items-center gap-1" accessible={false}>
                    <TypingDot delay={0} dim={reduceMotion} />
                    <TypingDot delay={140} dim={reduceMotion} />
                    <TypingDot delay={280} dim={reduceMotion} />
                  </View>
                </View>
              </View>
            ) : null
          }
        />

        {/* Composer — attach disc, growing field, send armed only with text.
            Individual floats over the stream — no band, iOS 26 idiom. */}
        <View
          pointerEvents="box-none"
          onLayout={(e) => setComposerH(e.nativeEvent.layout.height)}
          className="absolute inset-x-0 bottom-0 flex-row items-end gap-2 px-3 pt-3"
          style={{ paddingBottom: insets.bottom + 4 }}
        >
          <Button
            variant="glass"
            size="icon"
            haptic="light"
            onPress={onAttach}
            accessibilityLabel="Add attachment"
          >
            <Icon name="plus" size="md" color="secondaryForeground" />
          </Button>
          <View className="flex-1">
            <Input
              placeholder="Message…"
              value={draft}
              onChangeText={setDraft}
              onSubmitEditing={send}
              returnKeyType="send"
              // iMessage composer idiom — a pill field with dictation at rest.
              className="rounded-full"
              glass
              rightIcon={
                <Icon name="mic" size="sm" color="mutedForeground" />
              }
              accessibilityLabel="Message input"
            />
          </View>
          <Button
            size="icon"
            className="bg-[#1B1B26]"
            haptic="medium"
            disabled={draft.trim().length === 0}
            onPress={send}
            accessibilityLabel="Send message"
            accessibilityState={{ disabled: draft.trim().length === 0 }}
          >
            {/* iMessage idiom — an up-arrow in a filled circle, not a plane. */}
            <Icon name="arrow-up" size="sm" color="#FFFFFF" />
          </Button>
        </View>
      </KeyboardAvoiding>
    </SafeAreaView>
  );
}
```

Screen: https://lumioui.dev/screens/chat-chat-thread
iPhone 17 · iOS
9:41
Live preview — the real screen via Expo Web · open full ↗