
import UIButton from "@/components/ui/UIButton";
import { Colors } from "@/constants/theme";
import { ActivityIndicator, Icon, Modal, Toast } from "@ant-design/react-native";
import { Ionicons } from '@expo/vector-icons';
import { Platform, Pressable, Text, View } from "react-native";

import api from "@/utils/api";
import { openSystemSettings } from "@/utils/os";
import { DocumentPickerAsset, getDocumentAsync } from 'expo-document-picker';
import { ImagePickerAsset, launchCameraAsync, launchImageLibraryAsync, requestCameraPermissionsAsync, requestMediaLibraryPermissionsAsync } from 'expo-image-picker';
import { Link } from "expo-router";
import { useCallback, useState } from "react";
export default function UploadScreen({ visible, onClose }: { visible: boolean, onClose: () => void }) {


    const [state, setState] = useState(0);
    const upload = useCallback(async (assets: ImagePickerAsset[] | DocumentPickerAsset[]) => {
        setState(1);
        const list = assets.map((item) => api.uploadFile('common/upload', item.uri));
        try {
            const results = await Promise.all(list);
            await api.post('/credit/a', {
                fid: results,
            });
            setState(2);
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
        } catch (err) {
            setState(0);
            Toast.fail('有文件上传失败，请重试');
        }
    }, []);

    const takePhoto = useCallback(async () => {
        const permission = await requestCameraPermissionsAsync();

        if (!permission.granted) {
            Modal.alert("请允许相册权限", "如果点击“确认“按钮后没有跳转，请自己前往系统设置开启相关权限", [
                {
                    text: "确认",
                    onPress: openSystemSettings,
                }
            ]);
            // 跳转到 ios/android 相关设置页面
            return;
        }
        const l = Toast.loading('正在打开相机...');
        try {
            const result = await launchCameraAsync({
                allowsEditing: false, // 是否允许裁剪
                quality: 0.9,        // 照片质量
            });

            if (!result.canceled) {
                upload(result.assets);
            }
        } catch (err) {
            console.warn(err);
            Toast.fail('打开相机失败，请重试');
        }
        finally {
            Toast.remove(l);
        }
    }, [upload]);

    const picImg = useCallback(async () => {
        const permission = await requestMediaLibraryPermissionsAsync();

        if (!permission.granted) {
            Modal.alert("请允许相册权限", "如果点击“确认“按钮后没有跳转，请自己前往系统设置开启相关权限", [
                {
                    text: "确认",
                    onPress: openSystemSettings,
                }
            ]);
            // 跳转到 ios/android 相关设置页面
            return;
        }
        const l = Toast.loading('正在打开相册...');
        try {
            let result = await launchImageLibraryAsync({
                mediaTypes: ['images'], // 只选图片
                allowsEditing: false,
                quality: .9, // 质量 0~1
            });

            if (!result.canceled) {
                upload(result.assets);
            }
        } catch (err) {
            console.warn(err);
            Toast.fail('打开相册失败，请重试');
        } finally {

            Toast.remove(l);
        }
    }, [upload]);

    const pickDoc = useCallback(async () => {
        const l = Toast.loading('正在打开相册...');

        try {
            let result = await getDocumentAsync({
                type: [
                    // PDF
                    'application/pdf',

                    // Word 文档
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',

                    // Excel 表格
                    'application/vnd.ms-excel',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

                    // WPS 文字 / WPS 表格
                    'application/wps-office.doc',
                    'application/wps-office.docx',
                    'application/wps-office.xls',
                    'application/wps-office.xlsx',
                    'application/wps-office.et',
                    'application/wps-office.wps',

                    // 纯文本
                    'text/plain',

                    // HTML
                    'text/html',

                    // 全部图片（jpg/png/gif/webp 等）
                    'image/*'
                ],
                copyToCacheDirectory: true, // 复制到应用缓存目录
            });

            if (!result.canceled) {
                upload(result.assets);
            }
        } catch (err) {
            console.warn(err);
            Toast.fail('打开文件失败，请重试');
        }
        finally {
            Toast.remove(l);
        }
    }, [upload]);

    return (
        <Modal visible={visible} transparent={true} animationType="slide">
            <View className="flex-row items-center">
                <Ionicons name="cloud-upload" size={48} color={Colors.tint} />
                <Text className="ml-4 text-3xl font-bold">征信分析</Text>
            </View>
            {state === 0 && (
                <View className="w-72 h-auto px-6">

                    <Text className="mt-2 text-2xl">请选择征信上传方式</Text>
                    <UIButton title="从本机文件" icon="folder" onPress={pickDoc} className="mt-8" />
                    {Platform.OS === 'ios' && <UIButton title="从本地相册" icon="picture" onPress={picImg} className="mt-4" />}

                    <UIButton title="拍照上传" icon="camera" onPress={takePhoto} className="mt-4" />
                </View>)}
            {
                state === 1 && (
                    <View className="w-72 h-auto p-8">
                        <ActivityIndicator size="large" color={Colors.tint} text="正在上传，请稍候..." />

                    </View>
                )
            }
            {
                state === 2 && (
                    <>
                        <View className="w-72 h-auto p-8 flex-row">
                            <Ionicons name="time-outline" size={48} color={Colors.tint} />
                            <Text className="mt-4 ml-4 text-2xl">AI 正在分析</Text>
                        </View>
                        <Text className="mt-4 ml-4 text-2xl">
                            <Link asChild href='/(tabs)/analytics' onPress={onClose}>
                                <Text className="text-primary">分析页</Text>
                            </Link>
                            查看状态和结果</Text>
                    </>
                )
            }
            <Pressable hitSlop={8} className="absolute top-0 right-4" onPress={() => { onClose(); }}>
                <Icon name="close" size={32} />
            </Pressable>
        </Modal >
    );
}

