import { useState, useEffect } from 'react'
import {
    View,
    Text,
    StyleSheet,
    ScrollView,
    Dimensions,
    Pressable,
    TextInput,
    StatusBar as RNStatusBar,
    Platform,
    KeyboardAvoidingView,
} from 'react-native'
import { StatusBar } from 'expo-status-bar'
import { SafeAreaView } from 'react-native-safe-area-context'
import { Image } from 'expo-image'
import { useRouter, useLocalSearchParams } from 'expo-router'
import { useTranslation } from 'react-i18next'
import { LinearGradient } from 'expo-linear-gradient'

import { LeftArrowIcon, UploadIcon, WhitePointsIcon } from '@/components/icon'
import UploadReferenceImageDrawer from '@/components/drawer/UploadReferenceImageDrawer'
import { StartGeneratingNotification } from '@/components/ui'

const { height: screenHeight } = Dimensions.get('window')

interface TemplateData {
    id: number
    videoUrl: any
    thumbnailUrl: any
    title: string
    duration: string
}

export default function GenerateVideoScreen() {
    const { t } = useTranslation()
    const router = useRouter()
    const params = useLocalSearchParams()
    const [description, setDescription] = useState('')
    const [uploadedImage, setUploadedImage] = useState<any>(null)
    const [templateData, setTemplateData] = useState<TemplateData | null>(null)
    const [drawerVisible, setDrawerVisible] = useState(false)
    const [showNotification, setShowNotification] = useState(false)
    
    useEffect(() => {
        if (params.template && typeof params.template === 'string') {
            try {
                const parsed = JSON.parse(params.template) as TemplateData
                setTemplateData(parsed)
                // 使用缩略图作为上传的图片
                if (parsed.thumbnailUrl) {
                    setUploadedImage(parsed.thumbnailUrl)
                }
            } catch (error) {
                console.error('Failed to parse template data:', error)
            }
        }
    }, [params.template])

    return (
        <SafeAreaView 
            style={styles.container} 
            edges={Platform.OS === 'ios' ? ['top'] : ['top', 'bottom']}
        >
            <StatusBar style="light" />
            {Platform.OS === 'android' && (
                <RNStatusBar 
                    barStyle="light-content" 
                    backgroundColor="transparent" 
                    translucent 
                />
            )}
            <KeyboardAvoidingView
                style={styles.keyboardAvoidingView}
                behavior={Platform.OS === 'ios' ? 'padding' : undefined}
                keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
            >
                <ScrollView
                    style={styles.scrollView}
                    contentContainerStyle={styles.scrollContent}
                    showsVerticalScrollIndicator={false}
                    keyboardShouldPersistTaps="handled"
                >
                {/* 顶部导航栏 */}
                <View style={styles.header}>
                    <Pressable
                        style={styles.backButton}
                        onPress={() => router.back()}
                    >
                        <LeftArrowIcon />
                    </Pressable>
                </View>
                <View style={styles.content}>
                {/* 标题区域 */}
                <View style={styles.titleSection}>
                    <Text style={styles.title}> {templateData?.title}</Text>
                    <Text style={styles.subtitle}>
                    {templateData?.title }
                    </Text>
                </View>
                 
                <View style={styles.uploadContainer}>
                        {uploadedImage ? (
                            <Image
                                source={uploadedImage}
                                style={styles.uploadedImage}
                                contentFit="cover"
                            />
                        ) : (
                            <View style={styles.avatarPlaceholder}>
                                <View style={styles.avatarCircle} />
                            </View>
                        )}
                    <View style={styles.thumbnailContainer}>
                    <Image
                        source={templateData?.thumbnailUrl}
                        style={styles.thumbnail}
                        contentFit="cover"
                    />
                </View>
                </View>
                   {/* 上传区域 */}
                <Pressable
                    style={styles.uploadReferenceButton}
                    onPress={() => {
                        setDrawerVisible(true)
                    }}
                >
                    <UploadIcon />
                    <Text style={styles.uploadReferenceText}>{t('generateVideo.uploadReference')}</Text>
                </Pressable>
                {/* 描述输入区域 */}
                  <TextInput
                      style={styles.descriptionInput}
                      value={description}
                      onChangeText={setDescription}
                      placeholder={t('generateVideo.descriptionPlaceholder')}
                      placeholderTextColor="#8A8A8A"
                      multiline
                      numberOfLines={4}
                      textAlignVertical="top"
                  />
                {/* 底部生成按钮 */}
                <View style={styles.generateButtonContainer}>
                    <Pressable
                        onPress={() => {
                            setShowNotification(true)
                            // 3秒后自动隐藏通知
                            setTimeout(() => {
                                setShowNotification(false)
                            }, 3000)
                        }}
                    >
                        <LinearGradient
                            colors={['#9966FF', '#FF6699', '#FF9966']}
                            locations={[0.0015, 0.4985, 0.9956]}
                            start={{ x: 1, y: 0 }}
                            end={{ x: 0, y: 0 }}
                            style={styles.generateButton}
                        >
                            <Text style={styles.generateButtonText}>{t('generateVideo.generate')}</Text>
                            <View style={styles.pointsBadge}>
                                <WhitePointsIcon />
                                <Text style={styles.pointsText}>10</Text>
                            </View>
                        </LinearGradient>
                    </Pressable>
                </View>
                </View>
                </ScrollView>
            </KeyboardAvoidingView>
            <UploadReferenceImageDrawer
                visible={drawerVisible}
                onClose={() => setDrawerVisible(false)}
                onSelectImage={(imageUri) => {
                    setUploadedImage(imageUri)
                }}
            />
            {/* 通知组件 */}
            {showNotification && (
                <View style={styles.notificationContainer}>
                    <StartGeneratingNotification
                        count={1}
                        visible={showNotification}
                        title={t('generateVideo.startGenerating')}
                        message={t('generateVideo.generatingMessage')}
                        onPress={() => setShowNotification(false)}
                        style={styles.notification}
                    />
                </View>
            )}
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#090A0B',
    },
    keyboardAvoidingView: {
        flex: 1,
    },
    scrollView: {
        flex: 1,
        backgroundColor: '#090A0B',
    },
    scrollContent: {
        flexGrow: 1,
        backgroundColor: '#090A0B',
    },
    generateButtonContainer: {
        marginTop: 'auto',
        paddingTop: 12,
        paddingBottom: Platform.select({
            ios: 10,
            android: 10,
            default: 10,
        }),
    },
    content: {
        paddingHorizontal: 12,
        paddingTop: 16,
        backgroundColor: '#1C1E20',
        borderTopLeftRadius: 20,
        borderTopRightRadius: 20,
        gap: 8,
        minHeight: Platform.select({
            ios: screenHeight - 100,
            android: screenHeight - 100,
            default: screenHeight - 60,
        }),
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingTop: Platform.select({
            ios: 17,
            android: 12,
            default: 17,
        }),
        paddingHorizontal: 12,
        paddingBottom: 20,
    },
    backButton: {
        width: 22,
        height: 22,
        alignItems: 'center',
        justifyContent: 'center',
    },
    titleSection: {
        paddingHorizontal:4,
        marginBottom: 11,
    },
    title: {
        color: '#F5F5F5',
        fontSize: 16,
        fontWeight: '600',
        marginBottom: 5,
        marginLeft: -4,
    },
    subtitle: {
        color: '#CCCCCC',
        fontSize: 12,
    },

    uploadContainer: {
        height: 140,
        borderRadius: 12,
        backgroundColor: '#262A31',
        overflow: 'hidden',
        position: 'relative',
        alignItems: 'center',
        justifyContent: 'center',
    },
    thumbnailContainer: {
        position: 'absolute',
        left: 8,
        bottom: 5,
        width: 56,
        height: 56,
        borderRadius: 8,
        overflow: 'hidden',
        borderWidth: 2,
        borderColor: '#FFFFFF',
        backgroundColor: '#090A0B',
    },
    thumbnail: {
        width: '100%',
        height: '100%',
    },
    avatarPlaceholder: {
        width: 56,
        height: 56,
        borderRadius: 28,
        backgroundColor: '#2F3134',
        alignItems: 'center',
        justifyContent: 'center',
    },
    avatarCircle: {
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: '#4A4C4F',
    },
    uploadedImage: {
        width: '100%',
        height: '100%',
    },
    uploadReferenceButton: {
        height: 110,
        backgroundColor: '#262A31',
        borderRadius: 12,
        alignItems: 'center',
        justifyContent: 'center',
        gap: 6,
    },
    uploadReferenceText: {
        color: '#F5F5F5',
        fontSize: 12,
        fontWeight: '500',
    },
    descriptionInput: {
        minHeight: 150,
        backgroundColor: '#262A31',
        borderRadius: 12,
        padding: 12,
        color: '#F5F5F5',
        fontSize: 14,
        lineHeight: 20,
        ...Platform.select({
            android: {
                textAlignVertical: 'top',
            },
        }),
    },
    generateButton: {
        width: '100%',
        height: 48,
        backgroundColor: 'red',
        borderRadius: 12,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 8,
    },
    generateButtonText: {
        color: '#F5F5F5',
        fontSize: 16,
        fontWeight: '500',
    },
    pointsBadge: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    pointsText: {
        color: '#f5f5f5',
        fontSize: 14,
        fontWeight: '500',
    },
    notificationContainer: {
        position: 'absolute',
        top: Platform.select({
            ios: 60,
            android: 50,
            default: 60,
        }),
        left: 0,
        right: 0,
        paddingHorizontal: 8,
        zIndex: 1000,
    },
    notification: {
        width: '100%',
    },
})

