import { View, Text, Pressable, ScrollView } from "react-native";
import { ReactNode } from "react";
import { useThemeStore } from "../stores/ThemeStore";

type TextSize = "text-sm" | "text-base" | "text-lg" | "text-xl";

type CardBaseProps = {
  title: string;
  subtitle?: string;
  children: ReactNode;
  attachment?: ReactNode; // renders between children and footer
  footer?: {
    label: string;
    onPress: () => void;
  };
  className?: string;
  scrollable?: boolean;
  maxContentHeight?: number;
  borderWidth?: number;
  headerBorderWidth?: number;
  headerPadding?: number;
  contentPadding?: number;
  headerTextSize?: TextSize;
  contentBg?: string;
};

export const CardBase = ({
  title,
  subtitle,
  children,
  attachment,
  footer,
  className = "",
  scrollable = false,
  maxContentHeight,
  borderWidth = 2,
  headerBorderWidth,
  headerPadding,
  contentPadding,
  headerTextSize = "text-base",
  contentBg,
}: CardBaseProps) => {
  const { theme } = useThemeStore();
  const effectiveHeaderBorderWidth = headerBorderWidth ?? borderWidth;

  const headerPaddingClass = headerPadding ? `p-${headerPadding}` : "px-3 py-2";
  const contentPaddingClass = contentPadding
    ? `p-${contentPadding}`
    : "px-3 py-2";

  const contentElement = (
    <View
      className={contentPaddingClass}
      style={{ backgroundColor: contentBg ?? theme.secondaryBg }}
    >
      {children}
    </View>
  );

  return (
    <View
      className={`rounded-xl overflow-hidden ${className}`}
      style={{ borderWidth, borderColor: theme.borderPrimary }}
    >
      {/* Header */}
      <View
        className={headerPaddingClass}
        style={{
          backgroundColor: theme.chatBot,
          borderBottomWidth: effectiveHeaderBorderWidth,
          borderBottomColor: theme.borderPrimary,
        }}
      >
        <Text
          className={`font-bold ${headerTextSize}`}
          style={{ color: theme.textPrimary }}
        >
          {title}
        </Text>
        {subtitle && (
          <Text style={{ color: theme.primeFg }} numberOfLines={1}>
            {subtitle}
          </Text>
        )}
      </View>

      {/* Content */}
      {scrollable ? (
        <ScrollView
          style={{ maxHeight: maxContentHeight }}
          nestedScrollEnabled={true}
        >
          {contentElement}
        </ScrollView>
      ) : (
        contentElement
      )}

      {attachment}

      {/* Footer (optional) */}
      {footer && (
        <Pressable
          onPress={footer.onPress}
          className="py-3 items-center"
          style={{
            borderTopWidth: 1,
            borderTopColor: theme.placeholderBg,
          }}
        >
          <Text style={{ color: theme.primeFg }} className="font-bold">
            {footer.label}
          </Text>
        </Pressable>
      )}
    </View>
  );
};

export default CardBase;
