import { useState } from 'react';

const useSupportPopup = () => {
    const [isOpen, setIsOpen] = useState(false);
    const [copiedItemIndex, setCopiedItemIndex] = useState(null);
    const [error, setError] = useState(null);

    // Support configuration
    const SUPPORT_CONFIG = {
        email: 'support@wppool.dev',
        subject: 'Support Request: Echo Rewards',
        body: 'Hello WPPOOL Team,\n\nI need assistance with Echo Rewards. Here are the details of my issue:\n\n[Please describe your issue here]\n\nThank you,\n[Your Name]'
    };

    // Email client configurations
    const EMAIL_CLIENTS = {
        gmail: {
            urlTemplate: 'https://mail.google.com/mail/?view=cm&fs=1&to={email}&su={subject}&body={body}'
        },
        outlook: {
            urlTemplate: 'https://outlook.office.com/mail/deeplink/compose?to={email}&subject={subject}&body={body}'
        },
        yahoo: {
            urlTemplate: 'https://compose.mail.yahoo.com/?to={email}&subject={subject}&body={body}'
        },
        default: {
            urlTemplate: 'mailto:{email}?subject={subject}&body={body}'
        }
    };

    // Modal state management functions
    const openSupportPopup = () => {
        setIsOpen(true);
        setError(null); // Clear any previous errors
    };
    const closeSupportPopup = () => {
        setIsOpen(false);
        setError(null); // Clear errors when closing
    };
    const toggleSupportPopup = () => {
        setIsOpen(!isOpen);
        if (!isOpen) {
            setError(null); // Clear errors when opening
        }
    };

    // Email redirection handler with enhanced error handling
    const handleEmailRedirect = (emailType) => {
        try {
            const { email, subject, body } = SUPPORT_CONFIG;
            const client = EMAIL_CLIENTS[emailType];
            
            if (!client) {
                console.warn(`Unknown email client: ${emailType}`);
                setError(`Unsupported email client: ${emailType}`);
                return;
            }

            // Validate email configuration
            if (!email || !subject) {
                console.error('Invalid support configuration');
                setError('Support configuration is invalid');
                return;
            }

            let mailtoUrl = client.urlTemplate
                .replace('{email}', email)
                .replace('{subject}', encodeURIComponent(subject))
                .replace('{body}', encodeURIComponent(body));

            // Validate URL before opening
            if (!mailtoUrl || mailtoUrl.length < 10) {
                throw new Error('Generated URL is invalid');
            }

            // Open in a new tab/window
            const newWindow = window.open(mailtoUrl, '_blank');
            
            // Check if popup was blocked
            if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
                throw new Error('Popup blocked by browser');
            }

            setError(null); // Clear any previous errors on success
        } catch (error) {
            console.error('Failed to open email client:', error);
            setError('Failed to open email client. Please try copying the email address instead.');
            
            // Fallback to basic mailto
            try {
                const fallbackUrl = `mailto:${SUPPORT_CONFIG.email}`;
                const fallbackWindow = window.open(fallbackUrl, '_blank');
                
                if (!fallbackWindow || fallbackWindow.closed || typeof fallbackWindow.closed === 'undefined') {
                    setError('Unable to open email client. Please copy the email address and contact us manually.');
                }
            } catch (fallbackError) {
                console.error('Fallback email client failed:', fallbackError);
                setError('Unable to open email client. Please copy the email address: support@wppool.dev');
            }
        }
    };

    // Clipboard copy handler with enhanced error handling
    const handleCopy = async (text, index) => {
        try {
            // Validate input
            if (!text || typeof text !== 'string') {
                throw new Error('Invalid text to copy');
            }

            // Try modern clipboard API first
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(text);
                setCopiedItemIndex(index);
                setError(null); // Clear any previous errors
                
                // Reset copied state after 2 seconds
                setTimeout(() => {
                    setCopiedItemIndex(null);
                }, 2000);
            } else {
                // Fallback for older browsers or non-secure contexts
                const textArea = document.createElement('textarea');
                textArea.value = text;
                textArea.style.position = 'fixed';
                textArea.style.left = '-999999px';
                textArea.style.top = '-999999px';
                textArea.style.opacity = '0';
                textArea.setAttribute('readonly', '');
                textArea.setAttribute('aria-hidden', 'true');
                
                document.body.appendChild(textArea);
                
                try {
                    textArea.focus();
                    textArea.select();
                    textArea.setSelectionRange(0, 99999); // For mobile devices
                    
                    const successful = document.execCommand('copy');
                    if (!successful) {
                        throw new Error('Copy command failed');
                    }
                    
                    setCopiedItemIndex(index);
                    setError(null); // Clear any previous errors
                    
                    // Reset copied state after 2 seconds
                    setTimeout(() => {
                        setCopiedItemIndex(null);
                    }, 2000);
                } catch (err) {
                    console.error('Fallback copy failed:', err);
                    setError('Failed to copy to clipboard. Please manually copy: ' + text);
                } finally {
                    document.body.removeChild(textArea);
                }
            }
        } catch (error) {
            console.error('Failed to copy to clipboard:', error);
            setError('Failed to copy to clipboard. Please manually copy the email address.');
        }
    };

    // Clear error function
    const clearError = () => setError(null);

    return {
        isOpen,
        openSupportPopup,
        closeSupportPopup,
        toggleSupportPopup,
        handleEmailRedirect,
        handleCopy,
        copiedItemIndex,
        error,
        clearError
    };
};

export default useSupportPopup;