import React, { useEffect } from 'react';
import { isMobile, isAndroid, isIOS } from 'react-device-detect';

export const SMSShare = ({ message, mobileNumber, onClose }) => {
  useEffect(() => {
    const encodedMessage = encodeURIComponent(message);
    const number = mobileNumber;

    const openSMS = () => {
      if (!number) {
        console.error('Mobile number is required');
        if (onClose) onClose();
        return;
      }

      let smsUrl;

      if (isIOS) {
        // iOS format
        smsUrl = `sms:${number}&body=${encodedMessage}`;
      } else if (isAndroid) {
        // Android format
        smsUrl = `sms:${number}?body=${encodedMessage}`;
      } else if (isMobile) {
        // Generic mobile format
        smsUrl = `sms:${number}?body=${encodedMessage}`;
      } else {
        // Desktop/Web - try multiple approaches
        const webSMSOptions = [
          `sms:${number}?body=${encodedMessage}`,
          `sms://${number}?body=${encodedMessage}`,
          // Fallback to web SMS services
          `https://web.whatsapp.com/send?phone=${number}&text=${encodedMessage}`,
          `https://messages.google.com/web/conversations/new?recipient=${number}&body=${encodedMessage}`,
        ];

        // Try the first SMS URL
        smsUrl = webSMSOptions[0];

        // If SMS doesn't work on desktop, provide alternatives
        const tryAlternatives = () => {
          // Try opening web-based messaging
          const userChoice = window.confirm(
            'SMS app not available. Would you like to try WhatsApp Web instead?'
          );

          if (userChoice) {
            window.open(webSMSOptions[2], '_blank');
          } else {
            // Copy to clipboard as fallback
            const textToCopy = `To: ${number}\nMessage: ${message}`;
            navigator.clipboard
              .writeText(textToCopy)
              .then(() => {
                alert('Message details copied to clipboard!');
              })
              .catch(() => {
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = textToCopy;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('Message details copied to clipboard!');
              });
          }
        };

        // For desktop, try SMS first, then fallback
        try {
          const newWindow = window.open(smsUrl, '_blank');

          // Check if window opened successfully
          setTimeout(() => {
            if (
              newWindow &&
              (newWindow.closed || newWindow.location.href === 'about:blank')
            ) {
              newWindow.close();
              tryAlternatives();
            }
          }, 1000);
        } catch (error) {
          console.error('SMS open failed:', error);
          tryAlternatives();
        }

        if (onClose) {
          setTimeout(() => onClose(), 1500);
        }
        return;
      }

      // For mobile devices
      try {
        // Try to open SMS app
        window.location.href = smsUrl;

        // Alternative method if location.href doesn't work
        setTimeout(() => {
          try {
            window.open(smsUrl, '_self');
          } catch (error) {
            console.error('Failed to open SMS app:', error);
            // Fallback: copy to clipboard
            navigator.clipboard.writeText(`${number}: ${message}`).then(() => {
              alert('SMS app not available. Message copied to clipboard!');
            });
          }
        }, 100);
      } catch (error) {
        console.error('SMS open failed:', error);
        // Fallback for mobile
        navigator.clipboard.writeText(`${number}: ${message}`).then(() => {
          alert('SMS app not available. Message copied to clipboard!');
        });
      }

      if (onClose) {
        setTimeout(() => onClose(), 500);
      }
    };

    // Small delay to ensure component is mounted
    const timer = setTimeout(openSMS, 100);

    return () => clearTimeout(timer);
  }, [message, mobileNumber, onClose]);

  return null;
};

export default SMSShare;
