import type { FC, ReactElement } from 'react';
import React from 'react';
import type { TextStyle } from 'react-native';
import { Text, View, Pressable } from 'react-native';
import { useTheme } from '../../branding';
import themedStyles from './styles';
import Close from '../Icons/Close';
import { formatMessage } from '../../i18n';

type TitleAlign = 'left' | 'center' | 'right';

interface HeaderProps {
    title: string | ReactElement;
    onBottomSheetClose: () => void;
    onReset?: () => void;
    titleAlign?: TitleAlign;
    showCloseButton?: boolean;
}

const Header: FC<HeaderProps> = ({
    title,
    onBottomSheetClose,
    onReset,
    titleAlign = 'center',
    showCloseButton = true
}) => {
    const { theme } = useTheme();
    const styles = themedStyles[theme];

    const titleAlignmentStyles = {
        left: styles.titleLeft,
        center: styles.titleCenter,
        right: styles.titleRight
    };

    const titleContainerStyles = [
        styles.titleContainer,
        titleAlignmentStyles[titleAlign] || {},
        showCloseButton && titleAlign === 'left' && styles.headerWithCloseLeft
    ];

    const renderTitle = () => {
        if (React.isValidElement(title)) {
            return title;
        }
        return <Text style={styles.title as TextStyle}>{title}</Text>;
    };

    return (
        <View style={styles.header}>
            <View style={titleContainerStyles}>{renderTitle()}</View>

            {showCloseButton && (
                <Pressable
                    hitSlop={15}
                    onPress={onBottomSheetClose}
                    testID="closeButton"
                    style={({ pressed }) => [
                        styles.closeButton,
                        pressed && styles.pressedCloseButton
                    ]}
                >
                    <Close size={24} />
                </Pressable>
            )}

            {onReset && (
                <Pressable
                    onPress={onReset}
                    hitSlop={15}
                    testID="resetButton"
                    style={({ pressed }) => [
                        styles.resetButton,
                        pressed && styles.pressedResetButton
                    ]}
                >
                    <Text style={styles.resetText as TextStyle}>
                        {formatMessage('filtering.reset')}
                    </Text>
                </Pressable>
            )}
        </View>
    );
};

export default Header;
