import { useState } from 'react';
import { FaShare } from 'react-icons/fa';
import { createPortal } from 'react-dom';
import styles from './PromptItemShare.module.css';
import { useAuthToken } from '../../../auth/Hooks/use-auth-token';
import { useOrgUsers } from '../../../auth/Hooks/get-all-users';
import { authorizedPost } from '../../../api';

interface PromptItemShareProps {
    promptId: string;
    promptTitle: string;
}

export const PromptItemShare: React.FC<PromptItemShareProps> = ({ promptId, promptTitle }) => {
    const [showModal, setShowModal] = useState(false);
    const [selectedUsers, setSelectedUsers] = useState<Set<string>>(new Set());
    const { getToken } = useAuthToken();
    const { users, loading, error } = useOrgUsers();

    const handleShareClick = () => {
        setShowModal(true);
    };

    const handleUserToggle = (userId: string) => {
        setSelectedUsers(prev => {
            const newSet = new Set(prev);
            if (newSet.has(userId)) {
                newSet.delete(userId);
            } else {
                newSet.add(userId);
            }
            return newSet;
        });
    };

    const handleShare = async () => {
        try {
            console.log(Array.from(selectedUsers));
            await authorizedPost(`/api/user/prompts/${promptId}/share`, getToken, {
                user_ids: Array.from(selectedUsers)
            });
            setShowModal(false);
            setSelectedUsers(new Set());
        } catch (error) {
            console.error('Error sharing prompt:', error);
        }
    };

    const handleCancel = () => {
        setShowModal(false);
        setSelectedUsers(new Set());
    };

    return (
        <>
            <button 
                className={styles.shareButton} 
                title="Share"
                onClick={handleShareClick}
            >
                <FaShare />
            </button>

            {showModal && createPortal(
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <h2>Share Prompt</h2>
                        <p>Share "{promptTitle}" with:</p>
                        
                        {loading && <div className={styles.loading}>Loading users...</div>}
                        {error && <div className={styles.error}>{error}</div>}
                        
                        <div className={styles.userList}>
                            {users.map(user => (
                                <label key={user.id} className={styles.userItem}>
                                    <input
                                        type="checkbox"
                                        checked={selectedUsers.has(user.id)}
                                        onChange={() => handleUserToggle(user.id)}
                                    />
                                    <span className={styles.userName}>
                                        {user.name}
                                        <span className={styles.userEmail}>({user.email})</span>
                                    </span>
                                </label>
                            ))}
                        </div>

                        <div className={styles.modalButtons}>
                            <button 
                                className={`${styles.modalButton} ${styles.cancelButton}`}
                                onClick={handleCancel}
                            >
                                Cancel
                            </button>
                            <button 
                                className={`${styles.modalButton} ${styles.shareButton}`}
                                onClick={handleShare}
                                disabled={selectedUsers.size === 0}
                            >
                                Share
                            </button>
                        </div>
                    </div>
                </div>,
                document.body
            )}
        </>
    );
};

export default PromptItemShare; 