import React, { useCallback, useRef, useState } from 'react';
import { Animated, Pressable, StyleSheet, Text, View, type ViewStyle } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../../theme';

interface CardProps {
  title?: string;
  children: React.ReactNode;
  onPress?: () => void;
  onLongPress?: () => void;
  style?: ViewStyle;
  /** 是否开启折叠/展开功能。 */
  collapsible?: boolean;
  /** 默认是否呈收起状态(仅当 collapsible 为 true 时生效)。 */
  defaultCollapsed?: boolean;
}

/** 卡片容器（主题化，并有触控微交互与可选折叠展开功能）。 */
export function Card({ title, children, onPress, onLongPress, style, collapsible, defaultCollapsed }: CardProps) {
  const { theme } = useTheme();
  const scale = useRef(new Animated.Value(1)).current;
  const [isCollapsed, setIsCollapsed] = useState(collapsible ? (defaultCollapsed ?? false) : false);

  const handlePressIn = useCallback(() => {
    Animated.spring(scale, {
      toValue: 0.98,
      useNativeDriver: true,
      tension: 150,
      friction: 7,
    }).start();
  }, [scale]);

  const handlePressOut = useCallback(() => {
    Animated.spring(scale, {
      toValue: 1.0,
      useNativeDriver: true,
      tension: 150,
      friction: 7,
    }).start();
  }, [scale]);

  const cardStyle = {
    backgroundColor: theme.colors.bgSecondary,
    borderRadius: theme.radii.xl,
    padding: theme.spacing.md,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: theme.colors.border,
    ...theme.shadows.sm,
  };

  const isInteractive = Boolean(onPress || onLongPress);

  if (collapsible) {
    return (
      <View style={[styles.card, cardStyle, style]}>
        <Pressable
          onPress={() => setIsCollapsed(prev => !prev)}
          style={styles.headerRow}
          hitSlop={4}
        >
          <Text
            style={[
              styles.title,
              { color: theme.colors.fgPrimary, flex: 1, marginBottom: 0 },
              theme.typography.h3,
            ]}
          >
            {title}
          </Text>
          <Ionicons
            name={isCollapsed ? 'chevron-down' : 'chevron-up'}
            size={18}
            color={theme.colors.fgSecondary}
          />
        </Pressable>
        {!isCollapsed && <View style={styles.collapsibleContent}>{children}</View>}
      </View>
    );
  }

  if (isInteractive) {
    return (
      <Pressable
        onPress={onPress}
        onLongPress={onLongPress}
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
        style={style}
      >
        <Animated.View
          style={[
            styles.card,
            cardStyle,
            { transform: [{ scale }] },
          ]}
        >
          {title ? (
            <Text
              style={[
                styles.title,
                { color: theme.colors.fgPrimary },
                theme.typography.h3,
              ]}
            >
              {title}
            </Text>
          ) : null}
          {children}
        </Animated.View>
      </Pressable>
    );
  }

  return (
    <View
      style={[
        styles.card,
        cardStyle,
        style,
      ]}
    >
      {title ? (
        <Text
          style={[
            styles.title,
            { color: theme.colors.fgPrimary },
            theme.typography.h3,
          ]}
        >
          {title}
        </Text>
      ) : null}
      {children}
    </View>
  );
}

const styles = StyleSheet.create({
  card: { gap: 8 },
  title: { marginBottom: 4 },
  headerRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 2 },
  collapsibleContent: { marginTop: 4, gap: 8 },
});
