import React, { useRef, useState } from "react";
import {
    Modal,
    View,
    Text,
    Image,
    TouchableOpacity,
    StyleSheet, ActionSheetIOS,
} from "react-native";
import * as ImagePicker from "react-native-image-crop-picker";
import ViewShot from "react-native-view-shot";
import { Ionicons } from "./icons";
import Share from "react-native-share";
import AndroidShareModal from "./AndroidShareModal";

export default function BadgeModal({ visible, onClose, onSave }) {
    // Android share modal state
    const [shareUri, setShareUri] = useState(null);
    const [showShareModal, setShowShareModal] = useState(false);
    const [photo, setPhoto] = useState(null);
    const shotRef = useRef(null);

    const openCamera = () => {
        ImagePicker.openCamera({
            width: 300, // crop width 
            height: 400,
            cropping: true,
            //freeStyleCropEnabled: true,   // allows user to crop any way they want
            cropperToolbarTitle: "Crop your selfie", // optional
            compressImageQuality: 0.8, // optional
            mediaType: 'photo',
            useFrontCamera: true, // selfie only
        })
            .then(image => {
                console.log(image.path);
                setPhoto(image.path); // set captured & cropped photo
            })
            .catch(e => {
                if (e.code === 'E_PICKER_CANCELLED') {
                    console.log('User cancelled image picker');
                } else {
                    console.log('Error: ', e);
                }
            });
    };

    const sharePhoto = async () => {
        try {
            if (!shotRef.current) return;
            setTimeout(async () => {
                const uri = await shotRef.current.capture();
                onSave(uri);
                // setShareUri(uri);
                // setShowShareModal(true);
                onClose();
                setTimeout(() => {
                    setPhoto(null);
                }, 1000);
                const options = {
                    title: "Share Image",
                    url: uri,          // file:// or base64
                    type: "image/jpeg",
                };
                await Share.open(options);
            }, 100);
        } catch (error) {
            console.log("Share Error:", error);
        }
    };

    return (
        <>
            <Modal visible={visible} transparent animationType="fade">
                <View style={styles.overlay}>
                    <View style={styles.card}>

                        {/* CLOSE */}
                        <TouchableOpacity style={styles.closeBtn} onPress={onClose}>
                            <Text style={styles.closeText}>×</Text>
                        </TouchableOpacity>

                        {/* The layout that will be exported */}
                        <ViewShot ref={shotRef} options={{ format: "png", quality: 1, backgroundColor: "#FFFFFF", }}>
                            <View style={styles.badgeContainer}>

                                {/* Badge frame + photo */}
                                <View style={styles.centerWrapper}>
                                    <Image
                                        source={require("../assets/badge.png")}
                                        style={styles.badgeFrame}
                                        resizeMode="contain"
                                    />

                                    {photo && (
                                        <Image
                                            source={{ uri: photo }}
                                            style={styles.profilePhoto}
                                            onLoadEnd={() => console.log("Photo loaded")}
                                        />
                                    )}
                                </View>
                                {!photo ? (
                                    <Text
                                        style={{
                                            textAlign: 'center',
                                            fontSize: 20,
                                            lineHeight: 28,
                                            fontWeight: '500',
                                            paddingHorizontal: 20,
                                        }}
                                    >
                                        <Text style={{ fontWeight: '900', color: 'black' }}>
                                            Smile, Click, Celebrate!
                                        </Text>
                                        {'\n'}
                                        Take your Retail Day selfie!
                                        {'\n'}
                                        Share it on Instagram and tag
                                        {'\n'}
                                        <Text style={{ color: '#1a73e8', fontWeight: '600' }}>
                                            @cpmindiasm
                                        </Text>
                                    </Text>

                                ) : (
                                    <Text style={styles.subtext}>
                                        I’m a <Text style={styles.blue}>Retail Star</Text> with{"\n"}CPM India
                                    </Text>
                                )}

                            </View>
                        </ViewShot>

                        {/* ACTION BUTTONS */}

                        {!photo ? (
                            <TouchableOpacity style={[styles.shareBtn, { backgroundColor: "" }]} onPress={openCamera}>
                                <Ionicons name="camera" size={20} color="#000" style={{ marginRight: 8 }} />
                                <Text style={styles.shareText}>Take a Selfie</Text>
                            </TouchableOpacity>

                        ) : (
                            <View>
                                <TouchableOpacity style={[styles.shareBtn, { backgroundColor: "" }]} onPress={sharePhoto}>
                                    <Ionicons name="share" size={20} color="#000" style={{ marginRight: 8 }} />
                                    <Text style={styles.shareText}>Share with friends</Text>
                                </TouchableOpacity>

                                <TouchableOpacity style={[styles.retakeBtn, { backgroundColor: "#EDF7FF", marginTop: 20, padding: 5 }]} onPress={openCamera}>
                                    <Ionicons name="camera" size={20} color="#000" style={{ marginRight: 8 }} />
                                    <Text style={styles.shareText}>Click Selfie again</Text>
                                </TouchableOpacity>

                            </View>
                        )}
                    </View>
                </View>
            </Modal>

            <AndroidShareModal
                visible={showShareModal}
                imageUri={shareUri}
                onClose={() => setShowShareModal(false)}
            />
        </>
    );
}

const styles = StyleSheet.create({

    overlay: {
        flex: 1,
        backgroundColor: "rgba(0,0,0,0.6)",
        justifyContent: "center",
        alignItems: "center",
        paddingHorizontal: 5,
    },

    card: {
        width: "95%",
        backgroundColor: "#fff",
        borderRadius: 20,
        paddingBottom: 25,
        alignItems: "center",
    },

    closeBtn: {
        alignSelf: "flex-end",
        padding: 10,
    },

    closeText: {
        fontSize: 30,
        width: 40,               // circle width
        height: 40,              // circle height
        borderRadius: 20,        // half of width/height = circle
        backgroundColor: "#F2F2F2", // optional
        shadowOpacity: 0.2,
        shadowRadius: 4,
        textAlign: "center",
    },

    badgeContainer: {
        width: "100%",
        padding: 15,
        alignItems: "center",
        backgroundColor: "white"
    },

    bgImage: {
        ...StyleSheet.absoluteFillObject,
        opacity: 0.25,
        borderRadius: 20,
    },

    centerWrapper: {
        width: 300,
        height: 300,
        justifyContent: "center",
        alignItems: "center",
        marginBottom: 15,
        position: "relative",
        overflow: "hidden",  // clip the photo within the badge
    },

    badgeFrame: {
        width: "100%",
        height: "100%",
        position: "absolute",
    },

    profilePhoto: {
        width: 125,
        height: 125,
        borderRadius: 60,
        position: "absolute",
        top: "52.5%",           // move to center vertically
        left: "49%",
        transform: [{ translateX: -60 }, { translateY: -60 }], // offset half of width/height
        resizeMode: "cover",
    },

    subtextWithout: {
        fontSize: 16,
        fontWeight: "500",
        textAlign: "center",
        color: "#000",
    },
    subtext: {
        fontSize: 25,
        fontWeight: "900",
        textAlign: "center",
        color: "#000",
        lineHeight: 30,
    },

    blue: {
        color: "#1E73FF",   // same bright blue as your sample
        fontWeight: "900",
    },

    btn: {
        width: "90%",
        backgroundColor: "#1A73E8",
        paddingVertical: 14,
        borderRadius: 10,
        marginTop: 20,
    },

    btnText: {
        color: "#fff",
        fontSize: 18,
        textAlign: "center",
    },

    shareBtn: {
        flexDirection: "row",
        alignItems: "center",
        paddingVertical: 10,
        paddingHorizontal: 18,
        borderWidth: 1,
        borderColor: "#E0E0E0",
        borderRadius: 10,
        alignSelf: "center",
        backgroundColor: "#fff",
    },

    retakeBtn: {
        flexDirection: "row",
        alignItems: "center",
        paddingVertical: 5,
        paddingHorizontal: 10,
        borderWidth: 1,
        borderColor: "#EDF7FF",
        borderRadius: 15,
        alignSelf: "center",
        backgroundColor: "#EDF7FF",
    },

    shareText: {
        fontSize: 16,
        fontWeight: "600",
        color: "#000",       // same black text
    },

});
