import React from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import type { PostSummary } from '@ai-radar/shared';
import { useTheme } from '../theme/ThemeProvider';
import { textStyle, space, radius } from '../theme';
import { CategoryLabel } from './CategoryLabel';
import { SourceIcon } from './SourceIcon';
import { relativeTime } from '../lib/format';

/**
 * Story cards.
 *
 * Three treatments, matching the web's hierarchy. DESIGN.md caps this at
 * four deliberately — every extra card style is another decision the
 * reader has to make about what matters, and the whole product is a
 * promise that we already made it for them.
 *
 *   hero     the single most important thing today
 *   standard the rest of "important today"
 *   row      everything else: a scannable list, not a wall of cards
 */
type Variant = 'hero' | 'standard' | 'row';

export function StoryCard({
  post,
  variant = 'standard',
  onPress,
}: {
  post: PostSummary;
  variant?: Variant;
  onPress: (post: PostSummary) => void;
}) {
  const { palette, locale, rtl } = useTheme();
  const align = rtl ? ('right' as const) : ('left' as const);
  const dir = rtl ? ('rtl' as const) : ('ltr' as const);

  const titleKey = variant === 'hero' ? 'cardLg' : variant === 'row' ? 'row' : 'card';

  return (
    <Pressable
      onPress={() => onPress(post)}
      accessibilityRole="button"
      accessibilityLabel={post.title}
      style={({ pressed }) => [
        styles.base,
        variant !== 'row' && {
          backgroundColor: palette.surface,
          borderColor: palette.border,
          borderWidth: StyleSheet.hairlineWidth,
          borderRadius: radius.card,
          padding: space.s4,
        },
        variant === 'row' && {
          paddingVertical: space.s4,
          borderBottomColor: palette.border,
          borderBottomWidth: StyleSheet.hairlineWidth,
        },
        pressed && { opacity: 0.7 },
      ]}
    >
      <View style={[styles.head, { flexDirection: rtl ? 'row-reverse' : 'row' }]}>
        <CategoryLabel category={post.category} />
        {post.sponsored && (
          <Text style={[textStyle('label', locale), { color: palette.text3 }]}>
            {locale === 'ar' ? 'مموّل' : 'SPONSORED'}
          </Text>
        )}
      </View>

      <Text
        style={[
          textStyle(titleKey, locale),
          { color: palette.text, textAlign: align, writingDirection: dir, marginTop: space.s2 },
        ]}
        numberOfLines={variant === 'row' ? 3 : 4}
      >
        {post.title}
      </Text>

      {/* The row variant is a scan list: a summary under every row turns
          it back into a wall of cards, which is what it exists to avoid. */}
      {variant !== 'row' && (
        <Text
          style={[
            textStyle('bodySm', locale),
            { color: palette.text2, textAlign: align, writingDirection: dir, marginTop: space.s2 },
          ]}
          numberOfLines={variant === 'hero' ? 4 : 3}
        >
          {post.summary}
        </Text>
      )}

      {/* Why it matters is the product. On the hero it is worth the space. */}
      {variant === 'hero' && post.whyItMatters ? (
        <View
          style={[
            styles.why,
            {
              borderStartColor: palette.accent,
              backgroundColor: palette.surface2,
            },
          ]}
        >
          <Text
            style={[
              textStyle('label', locale),
              { color: palette.accent, textAlign: align, writingDirection: dir },
            ]}
          >
            {locale === 'ar' ? 'لماذا يهم' : 'WHY IT MATTERS'}
          </Text>
          <Text
            style={[
              textStyle('bodySm', locale),
              {
                color: palette.text2,
                textAlign: align,
                writingDirection: dir,
                marginTop: space.s1,
              },
            ]}
            numberOfLines={3}
          >
            {post.whyItMatters}
          </Text>
        </View>
      ) : null}

      <View style={[styles.meta, { flexDirection: rtl ? 'row-reverse' : 'row' }]}>
        <View style={[styles.metaLeft, { flexDirection: rtl ? 'row-reverse' : 'row' }]}>
          <SourceIcon src={post.sourceIconUrl} size={20} />
          <Text style={[textStyle('meta', locale), { color: palette.text3 }]} numberOfLines={1}>
            {[post.companyName ?? post.sourceName, relativeTime(post.publishedAt, locale)]
              .filter(Boolean)
              .join(' · ')}
          </Text>
        </View>
        {post.worthTrying === 'yes' && (
          <Text style={[textStyle('meta', locale), { color: palette.accent }]}>
            {locale === 'ar' ? '✓ يستحق التجربة' : '✓ Worth trying'}
          </Text>
        )}
      </View>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  base: {
    width: '100%',
  },
  head: {
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: space.s2,
  },
  why: {
    marginTop: space.s3,
    padding: space.s3,
    borderRadius: radius.chip,
    // Logical property: the rule sits on the correct side in RTL.
    borderStartWidth: 2,
  },
  meta: {
    marginTop: space.s3,
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: space.s2,
  },
  // flexShrink so a long company name truncates rather than pushing the
  // "worth trying" badge off the right edge of the card.
  metaLeft: {
    alignItems: 'center',
    gap: 6,
    flexShrink: 1,
  },
});
