import React from 'react';
import {
  type StyleProp,
  StyleSheet,
  TouchableOpacity,
  View,
  type ViewStyle,
} from 'react-native';
import CardContent from './CardContent';
import CardActions from './CardActions';
import CardCover from './CardCover';
import CardTitle from './CardTitle';
import { withTheme, useTheme } from '../../core/theming';
import type { Theme } from '../../utils/types';

type Props = {
  onPress?: () => void;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
  borderRadius?: number | undefined;
  borderWidth?: number | undefined;
  borderColor?: string | undefined;
  activeOpacity?: number;
  theme: Theme;
};

const TCard = ({
  onPress,
  children,
  style,
  borderRadius,
  borderWidth,
  borderColor,
  activeOpacity = 1,
}: Props): any => {
  const { colors } = useTheme();
  const stylesWithProp = styles({
    colors,
    borderRadius,
    borderWidth,
    borderColor,
  });

  return (
    <TouchableOpacity
      style={[stylesWithProp.container, style]}
      activeOpacity={activeOpacity}
      disabled={!onPress}
      onPress={onPress}
      accessible={false}
    >
      <View style={stylesWithProp.innerContainer}>
        {React.Children.map(children, (child) =>
          React.isValidElement(child) ? React.cloneElement(child, {}) : child
        )}
      </View>
    </TouchableOpacity>
  );
};

TCard.Content = CardContent;
TCard.Actions = CardActions;
TCard.Cover = CardCover;
TCard.Title = CardTitle;

const styles = (props: {
  colors: any;
  borderRadius: number | undefined;
  borderWidth?: number | undefined;
  borderColor?: string | undefined;
}) =>
  StyleSheet.create({
    innerContainer: {
      flexGrow: 1,
      flexShrink: 1,
      overflow: 'hidden',
      borderRadius: props.borderRadius,
      borderWidth: props.borderWidth,
      borderColor: props.borderColor,
    },
    container: {
      borderRadius: props.borderRadius,
      backgroundColor: props.colors.background,
    },
  });

export default withTheme(TCard);
