import React from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import { useStyles, useWidget } from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import {
  LLAlertWidgetDetail,
  LLAlertWidgetDetailProps,
} from './LLAlertWidgetDetail';
import { LLAlertWidgetLink, LLAlertWidgetLinkProps } from './LLAlertWidgetLink';

export type LLAlertWidgetBodyStyles = {
  container: ViewStyle;
};

export type LLAlertWidgetBodyProps =
  ComponentStyleProp<LLAlertWidgetBodyStyles> & {
    widgetId: string;
    onLinkPress?: (arg: { url: string }) => void;
    DetailComponent?: typeof LLAlertWidgetDetail;
    DetailComponentStyles?: LLAlertWidgetDetailProps['styles'];
    LinkComponent?: typeof LLAlertWidgetLink;
    LinkComponentStyles?: LLAlertWidgetLinkProps['styles'];
  };

export function LLAlertWidgetBody({
  widgetId,
  onLinkPress,
  DetailComponent = LLAlertWidgetDetail,
  LinkComponent = LLAlertWidgetLink,
  DetailComponentStyles,
  LinkComponentStyles,
  styles: stylesProp,
}: LLAlertWidgetBodyProps) {
  const styles = useStyles({
    componentStylesFn: getAlertWidgetBodyStyles,
    stylesProp,
  });
  const widget = useWidget({ widgetId });

  if (!widget) {
    return undefined;
  }

  const { text, image_url, link_label, link_url } = widget;

  return (
    <View style={styles.container}>
      <DetailComponent
        text={text}
        imageUrl={image_url}
        styles={DetailComponentStyles}
      />
      {!!link_label && !!link_url && (
        <LinkComponent
          label={link_label}
          url={link_url}
          onLinkPress={onLinkPress}
          styles={LinkComponentStyles}
        />
      )}
    </View>
  );
}

const getAlertWidgetBodyStyles: LLComponentStyleFn<LLAlertWidgetBodyStyles> = ({
  theme,
}) =>
  StyleSheet.create({
    container: {
      display: 'flex',
      flexDirection: 'column',
      marginBottom: 16,
      paddingHorizontal: 16,
    },
  });
