import React, { useState, useRef, useEffect } from 'react';
import { Popover, Button } from 'antd';
import axios from 'axios';
import { t } from 'i18next';

const SelectableParagraph = ({ content, surahNo, verseNo, onDetailClick }) => {
  const paragraphRef = useRef(null);
  const [selection, setSelection] = useState({
    text: '',
    position: { x: 0, y: 0 },
    visible: false
  });

  const handleTextSelect = (e) => {
    // e.preventDefault();
    // e.stopPropagation();

    const selection = window.getSelection();
    // console.log('selection', selection.toString());
    if (!selection || selection.toString().trim() === '') {
      setSelection(prev => ({ ...prev, visible: false }));
      return;
    }

    const range = selection.getRangeAt(0);
    const rect = range.getBoundingClientRect();
    
    setSelection({
      text: selection.toString(),
      position: {
        x: rect.left + (rect.width / 2),
        y: rect.bottom
      },
      visible: true
    });    
  };

  useEffect(() => { 

    // console.log('selection', selection);

     const handleClickOutside = (e) => {
      if (!paragraphRef.current?.contains(e.target)) {
        setSelection(prev => ({ ...prev, visible: false }));
      }
    };

    document.addEventListener('mouseup', handleClickOutside);

    return () => {
      document.removeEventListener('mouseup', handleClickOutside);
    };
    
  }, []);

  const handleAction = async () => {
    setSelection(prev => ({ ...prev, visible: false }));

    window.getSelection().empty();

    const detail = {
      selection: selection.text,
      surahNo: surahNo,
      verseNo: verseNo
    }
    onDetailClick(detail);
  };

  const popoverContent = (
    <div style={{ display: 'flex', gap: '8px' }}>
      {/* <Button size="small" onClick={() => handleAction('Copy')}>Copy</Button>
      <Button size="small" onClick={() => handleAction('Analyze')}>Analyze</Button> */}
      <Button size="small" onClick={() => handleAction()}>{t('surah.meta-tafsir')}</Button>
    </div>
  );

  return (
    <div ref={paragraphRef}>
      <Popover
        content={popoverContent}
        open={selection.visible}
        destroyOnHidden={true}

        // onOpenChange={(visible) => setSelection(prev => ({ ...prev, visible }))}
        trigger="click"
        placement="bottom"
        overlayStyle={{ 
          position: 'fixed',
          left: `${selection.position.x}px`,
          top: `${selection.position.y}px`,
          transform: 'translateX(-50%)',
          animation: '0s fadeIn'
        }}
        // overlayInnerStyle={{ padding: '8px' }}
      >
        <div
          onMouseUp={handleTextSelect}
          onTouchEnd={handleTextSelect}
          
          onMouseDown={(e) => {
            setSelection(prev => ({ ...prev, visible: false }));
          }}
        >
          {content}
        </div>
      </Popover>
    </div>
  );
};

export default SelectableParagraph;



// import React, { useState, useEffect } from 'react';
// import { Popover, Button } from 'antd';

// const SelectableParagraph = ({ content, index }) => {
//   const [selection, setSelection] = useState({
//     text: '',
//     position: { x: 0, y: 0 },
//     visible: false
//   });

//   useEffect(() => {
//     const handleMouseUp = (e) => {
//       const selection = window.getSelection();
//       const selectedText = selection.toString().trim();
      
//       // Only handle if selection is within this paragraph
//       if (!selectedText || !e.target.contains(selection.anchorNode)) {
//         if (selection.visible) {
//           setSelection(prev => ({ ...prev, visible: false }));
//         }
//         return;
//       }

//       const range = selection.getRangeAt(0);
//       const rect = range.getBoundingClientRect();
      
//       setSelection({
//         text: selectedText,
//         position: {
//           x: rect.left + (rect.width / 2),
//           y: rect.bottom
//         },
//         visible: true
//       });
//     };

//     document.addEventListener('mouseup', handleMouseUp);
//     return () => document.removeEventListener('mouseup', handleMouseUp);
//   }, []);

//   const handleAction = (action) => {
//     console.log(`${action} text:`, selection.text);
//     setSelection(prev => ({ ...prev, visible: false }));
//     window.getSelection().empty();
//   };

//   const popoverContent = (
//     <div style={{ display: 'flex', gap: '8px' }}>
//       <Button size="small" onClick={() => handleAction('Copy')}>Copy</Button>
//       <Button size="small" onClick={() => handleAction('Analyze')}>Analyze</Button>
//       <Button size="small" onClick={() => handleAction('Describe')}>Describe</Button>
//     </div>
//   );

//   return (
//     <Popover
//       content={popoverContent}
//       open={selection.visible}
//       onOpenChange={(visible) => {
//         if (!visible) setSelection(prev => ({ ...prev, visible: false }));
//       }}
//       trigger="click"
//       placement="bottom"
//       // overlayStyle={{ 
//       //   position: 'fixed',
//       //   left: `${selection.position.x}px`,
//       //   top: `${selection.position.y}px`,
//       //   transform: 'translateX(-50%)'
//       // }}
//       // overlayInnerStyle={{ padding: '8px' }}
//     >
//       <div>
//         {content}
//       </div>
//     </Popover>
//   );
// };
// export default SelectableParagraph;