import { api as apiCfg } from '@/config.json';
import { Colors } from '@/constants/theme';
import api from '@/utils/api';
import { Icon, Modal } from "@ant-design/react-native";
import { Image } from 'expo-image';
import { useCallback, useEffect, useRef, useState } from "react";
import { Pressable, TextInput, View } from 'react-native';

function bin2uri(data: Blob) {
    return new Promise<string>((resolve, reject) => {
      
        const reader = new FileReader();
        reader.onloadend = () => {
            resolve(reader.result as string);
        };
        reader.onerror = reject;
        reader.readAsDataURL(data);
    });
}
export 
interface CaptchaRes {
    ok: boolean;
    code?: string;
    sid?: string;
}

export default function CaptchaBox({ onClose, visible }: { onClose: (res: CaptchaRes) => void; visible: boolean }) {
    const [v, setVisible] = useState<boolean>(false);
    const [uri, setUri] = useState<string>(null!);
    const [value, setValue] = useState("");
    const idRef = useRef<string|undefined>(null);
    const resRef = useRef<CaptchaRes>({ok: false});

      const refresh = useCallback(async () => {
        try {
            const res = await api.rawRequest<Blob>({
                url: `${apiCfg.url}common/captcha&?t=${Date.now()}`,
                timeout: 15000,
                responseType: 'blob'
            });
            idRef.current = res.headers['x-session_id'] as string;
            setUri(await bin2uri(res.data));

        } catch (e) {
            console.error(e);
        }
    }, []);
    // alert(v)
    useEffect(()=> {
        setVisible(visible);
        setUri(null!);
        if (visible) {
            refresh();
            setValue('');
        }
    }, [refresh, visible]);
  


    return <Modal visible={v} transparent style={{width: 208}} onClose={()=>onClose(resRef.current)}
    
    footer={[
        {
            text: '取消',
            style: {color: Colors.textSecondary},
            onPress: ()=> {
                resRef.current!.ok = false;
                setVisible(false);
            }
        },
        {
            text: '确认',
            onPress: ()=> {
                // if (value.length !== 6) {
                //     Toast.fail("请输入 6 位字符");
                //     return;
                // }
                resRef.current!.ok = true;
                resRef.current.code = value;
                resRef.current.sid = idRef.current!;
                setVisible(false);   
            }
        }
    ]}
    >
        <View className='w-48 items-center justify-center'>
            <View className="w-full">
                {uri ? <Image style={{width: 175, height: 44}} className="w-full h-12 bg-gray-500" source={{ uri }} /> : <View className="w-full h-12 bg-gray-200" />}
                <Pressable className='w-8 h-8 p-1 justify-center items-center' onPress={refresh}><Icon name="reload" /></Pressable>
            </View>
            <View className="h-8 flex-row items-center rounded-2xl bg-surface-container-low p-0">

                <TextInput
                    value={value}
                    onChangeText={setValue}
                    keyboardType="phone-pad"
                    maxLength={6}
                    placeholder="请输入图中字符"
                    placeholderTextColor="#9ca3af"
                    className="flex-1 h-8 text-center p-0 text-sm font-medium text-on-surface"
                />
            </View>
        </View>
    </Modal>
}