import React from 'react';
import { Text } from 'react-native';
import type { ViewStyle } from 'react-native';
import TouchableOpacity from '../TouchableOpacity';
import styles from './styles';
import { track } from '../../services/analytics.service';
import * as linkingService from '../../services/linking.service';
import { EXTERNAL_LINK } from '../../constants/events';
import { withTheme } from '../../branding';
import type { ThemeProps } from '../../branding/hoc/types';
import LinkIcon from '../Icons/LinkIcon';

export const openURL = (url: string, params = {}) => {
    if (!url) {
        return;
    }
    track(EXTERNAL_LINK, { url, ...params });
    linkingService.openSafely(url);
};

interface WebLinkProps {
    style?: ViewStyle;
    title: string;
    url: string;
    testID?: string;
}

export const WebLink = ({
    style,
    title,
    url,
    testID,
    theme
}: WebLinkProps & ThemeProps) => (
    <TouchableOpacity
        style={[styles[theme].container, style]}
        onPress={() => openURL(url)}
        testID={testID}
    >
        <Text style={styles[theme].linkText}>{title}</Text>
        <LinkIcon />
    </TouchableOpacity>
);

export default withTheme(WebLink);
