import React, {useEffect, useMemo, useState} from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import Icon from './icon';
import {$Colors} from './style';

type RatingItemProp = {
    title: string;
    level: number;
    descType?: string[];
    onChange?: (data: {title: string; level: number}) => void;
    onPress?: (i: number) => void;
};

const defaultDescType = ['非常满意', '满意', '一般', '较差', '非常差'];
const descColor = [$Colors.secondary, $Colors.third, $Colors.fourth, $Colors.fourth, $Colors.fourth];

const stars = [0, 0, 0, 0, 0];
const RatingItem: React.FC<RatingItemProp> = ({level, title, onChange, onPress, descType = defaultDescType}) => {
    const desc = useMemo(() => descType[5 - level], [level, descType]);
    const color = useMemo(() => descColor[5 - level], [level]);
    const handlePress = (starIndex: number) => {
        onPress && onPress(starIndex + 1);
        onChange && onChange({level: starIndex + 1, title});
    };
    return (
        <View style={styles.ratingItem}>
            <Text style={styles.ratingTitle}>{title}</Text>
            {stars.map((star, index) => (
                <TouchableOpacity key={index} onPress={() => handlePress(index)} activeOpacity={0.9}>
                    <Icon name="star" color={level > index ? color : $Colors.grayII} style={styles.star} />
                </TouchableOpacity>
            ))}
            <Text style={styles.desc}>{desc}</Text>
        </View>
    );
};
export type RateStateProp = {
    title: string;
    level: number;
};
export type MakeRattingProps = {
    Rating: RateStateProp[];
    onChange?: (state: RateStateProp[]) => void;
    isDraft?: boolean;
    allowExpand?: boolean;
};

const MakeRating: React.FC<MakeRattingProps> = ({Rating, onChange, isDraft = false, allowExpand = true}) => {
    const [touched, setTouched] = useState(false);
    // const calcAverage = (arr: typeof state) => {
    //     return Math.round(arr.reduce((a, i) => a + i.level, 0) / arr.length);
    // };
    const handleUpdate = ({title: selectedTitle, level: newLevel}: RateStateProp) => {
        let isChange = false;
        const items = Rating.map((item) => {
            if (item.title === selectedTitle) {
                if (item.level !== newLevel) {
                    isChange = true;
                    return {...item, level: newLevel};
                }
            }
            return item;
        });

        if (isChange) {
            onChange && onChange(items);
        }
    };

    const handlePress = (newLevel: number) => {
        const newRating = Rating.map((rating) => {
            return {...rating, level: newLevel};
        });

        onChange && onChange(newRating);
        allowExpand && setTouched(true);
    };

    useEffect(() => {
        !allowExpand && setTouched(false);
    }, [allowExpand]);

    return (
        <View style={styles.wrapper}>
            {!isDraft && !touched ? (
                <RatingItem level={Rating[0].level} title={Rating[0].title} onPress={handlePress} key={Rating[0].title} />
            ) : (
                Rating.map((item) => <RatingItem level={item.level} title={item.title} onChange={handleUpdate} key={item.title} />)
            )}
        </View>
    );
};

export default MakeRating;

const styles = StyleSheet.create({
    wrapper: {
        display: 'flex',
        flexDirection: 'column',
        borderColor: $Colors.grayII,
        alignItems: 'flex-start',
    },
    ratingItem: {
        display: 'flex',
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        paddingTop: 6,
        paddingBottom: 6,
    },
    ratingTitle: {
        paddingRight: 10,
        color: $Colors.normalText,
        fontSize: 16,
    },
    star: {
        fontSize: 30,
        marginLeft: 4,
        marginRight: 4,
    },
    desc: {
        textAlign: 'right',
        fontSize: 14,
        color: $Colors.lighterText,
        flex: 1,
    },
});
