import React from 'react';
import { View, Text, Alert } from 'react-native';
import Animated, {
    interpolate,
    useAnimatedStyle,
    Extrapolation
} from 'react-native-reanimated';
import { safeWithTheme } from '../../branding';
import type { ThemeProps } from '../../branding/hoc/types';
import TouchableOpacity from '../../components/TouchableOpacity';
import { EXPANDED_CONTENT_HEIGHT, COLLAPSED_CONTENT_HEIGHT } from './constants';
import type { PageHeaderProps } from './types';
import styles from './styles';

const AnimatedView = Animated.View;

const describeProps = ({ loadingState }: PageHeaderProps): string => {
    if (loadingState.status !== 'data') {
        return `state: ${loadingState.status}`;
    }
    const { data } = loadingState;
    return [
        'state: data',
        `title: ${data.title}`,
        `subtitle: ${data.subtitle}`,
        `meta: ${data.meta}`,
        `imageUrl: ${data.imageUrl ?? '—'}`,
        `isDeleted: ${data.isDeleted}`,
        `isFavorite: ${data.isFavorite}`
    ].join('\n');
};

const PageHeader = (props: PageHeaderProps & ThemeProps) => {
    const { theme, progress, loadingState, onBackPress } = props;
    const { status } = loadingState;
    const themedStyle = styles[theme];

    const heightStyle = useAnimatedStyle(() => ({
        height: interpolate(
            progress.value,
            [0, 1],
            [EXPANDED_CONTENT_HEIGHT, COLLAPSED_CONTENT_HEIGHT],
            Extrapolation.CLAMP
        )
    }));

    const handleShowProps = () =>
        Alert.alert('PageHeader props', describeProps(props));

    return (
        <AnimatedView
            style={[themedStyle.container, heightStyle]}
            testID={`page-header-${status}`}
        >
            <View style={themedStyle.row}>
                <TouchableOpacity
                    onPress={onBackPress}
                    accessibilityRole="button"
                    accessibilityLabel="Back"
                >
                    <Text style={themedStyle.action}>{'< Back'}</Text>
                </TouchableOpacity>
                <Text style={themedStyle.label}>{`state: ${status}`}</Text>
                <TouchableOpacity
                    onPress={handleShowProps}
                    accessibilityRole="button"
                    accessibilityLabel="Show props"
                >
                    <Text style={themedStyle.action}>Show props</Text>
                </TouchableOpacity>
            </View>
        </AnimatedView>
    );
};

export default safeWithTheme<PageHeaderProps>(PageHeader);
