import PermissionAlert from '@/components/common/PermissionAlert';
import i18n from '@/i18n';
import { PermissionService } from '@/lib/PermissionService';
import React, { createContext, ReactNode, useCallback, useContext, useEffect, useState } from 'react';
import { Linking } from 'react-native';

interface PermissionAlertOptions {
    title: string;
    message: string;
    confirmText?: string;
    cancelText?: string;
}

interface PermissionContextType {
    showPermissionAlert: (options: PermissionAlertOptions) => Promise<boolean>;
}

interface AlertData {
    options: PermissionAlertOptions;
    resolve: (value: boolean) => void;
}

const PermissionContext = createContext<PermissionContextType | undefined>(undefined);

export const PermissionProvider = ({ children }: { children: ReactNode }) => {
    const [alertData, setAlertData] = useState<AlertData | null>(null);

    const showPermissionAlert = useCallback((options: PermissionAlertOptions) => {
        return new Promise<boolean>((resolve) => {
            setAlertData({ options, resolve });
        });
    }, []);

    useEffect(() => {
        PermissionService.set(showPermissionAlert);

        // Cleanup on unmount
        return () => {
            PermissionService.set(null as any); // or a no-op function
        };
    }, [showPermissionAlert]);

    const handleConfirm = () => {
        Linking.openSettings();
        if (alertData?.resolve) {
            alertData.resolve(true);
        }
        setAlertData(null);
    };

    const handleCancel = () => {
        if (alertData?.resolve) {
            alertData.resolve(false);
        }
        setAlertData(null);
    };

    return (
        <PermissionContext.Provider value={{ showPermissionAlert }}>
            {children}
            {alertData && (
                <PermissionAlert
                    visible={!!alertData}
                    title={alertData.options.title}
                    message={alertData.options.message}
                    confirmText={alertData.options.confirmText || i18n.t('permission:button.confirm')}
                    cancelText={alertData.options.cancelText || i18n.t('permission:button.cancel')}
                    onConfirm={handleConfirm}
                    onCancel={handleCancel}
                />
            )}
        </PermissionContext.Provider>
    );
};

export const usePermission = (): PermissionContextType => {
    const context = useContext(PermissionContext);
    if (!context) {
        throw new Error('usePermission must be used within a PermissionProvider');
    }
    return context;
};
