import React, { useState, useEffect } from 'react';
import axiosInstance from '../../src/axiosSecure';
import { toast } from 'react-toastify';
import { set } from 'date-fns';

function SearchReplacement({ shiftId, assignmentId }) {
    const [users, setUsers] = useState([]);
    const [showModal, setShowModal] = useState(false);

    const fetchUsers = async () => {
        // Dummy endpoint and shiftId, replace with actual
        const response = await axiosInstance.get('/api/?action=getPossibleShiftPublisherEmails&shiftId=' + shiftId);
        setUsers(response.data);
        setShowModal(true);
    };

    const sendCoverMeRequestByEmail = (selectedGroups) => {
        // You can map 'selectedGroups' to determine which API calls to make
        console.log("Selected Groups:", selectedGroups);
        axiosInstance.post('/api/email?action=sendCoverMeRequestByEmail', {
            assignmentId: assignmentId,
            toSubscribed: selectedGroups.includes('subscribedPublishers'),
            toAvailable: selectedGroups.includes('availablePublishers'),
        }).then(response => {
            console.log("response", response);
            setShowModal(false);
            //toast success and confirm the change
            toast.success("Заявката за заместник е изпратена!", {
                onClose: () => {
                    window.location.reload();
                }
            });
        }).catch(error => {
            console.log("error", error);
        });
    }

    return (
        <div>
            <button
                className="mr-2 mb-2 inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                onClick={() => fetchUsers(shiftId)}
            >
                Търси заместник
            </button>
            {
                showModal && (
                    <ConfirmationModal
                        isOpen={showModal}
                        onClose={() => setShowModal(false)}
                        onConfirm={sendCoverMeRequestByEmail}
                        subscribedPublishers={users.subscribedPublishers}
                        availablePublishers={users.availablePublishers}
                    />
                    // <ConfirmationModal
                    //     isOpen={showModal}
                    //     users={users}
                    //     onClose={() => setShowModal(false)}
                    //     onConfirm={(selectedUsers) => {
                    //         console.log(selectedUsers); // Here you would call the email API
                    //         setShowModal(false);
                    //     }}
                    // />
                )
            }
        </div >
    );
}

function ConfirmationModal({ isOpen, onClose, onConfirm, subscribedPublishers, availablePublishers }) {
    const [selectedGroups, setSelectedGroups] = useState([]);

    const handleToggleGroup = (groupName) => {
        setSelectedGroups(prev => {
            if (prev.includes(groupName)) {
                return prev.filter(name => name !== groupName);
            } else {
                return [...prev, groupName];
            }
        });
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 flex items-center justify-center z-50">
            <div className="absolute inset-0 bg-black opacity-50" onClick={onClose}></div>
            <div className="bg-white p-6 rounded-lg shadow-lg z-10 max-h-screen overflow-y-auto">
                <h2 className="text-lg font-semibold mb-4">Можете да изпратите заявка за заместник до следните групи:</h2>
                <div className="space-y-1">
                    <div className="flex items-center mb-2">
                        <input id="subscribedPublishersCheckbox"
                            type="checkbox"
                            className="mr-2 leading-tight"
                            checked={selectedGroups.includes('subscribedPublishers')}
                            onChange={() => handleToggleGroup('subscribedPublishers')}
                        />
                        <label htmlFor="subscribedPublishersCheckbox" className="text-sm font-medium">Абонирани:</label>
                    </div>
                    <div className="overflow-y-auto max-h-64">
                        <label className="block mb-2">
                            <div className="flex flex-wrap">
                                {subscribedPublishers.map(pub => (
                                    <span key={pub.id} className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">{pub.name}</span>
                                ))}
                            </div>
                        </label>
                    </div>
                    <div className="flex items-center mb-2">
                        <input id="availablePublishersCheckbox"
                            type="checkbox"
                            className="mr-2 leading-tight"
                            checked={selectedGroups.includes('availablePublishers')}
                            onChange={() => handleToggleGroup('availablePublishers')}
                        />
                        <label htmlFor="availablePublishersCheckbox" className="text-sm font-medium">На разположение :</label>
                    </div>
                    <div className="overflow-y-auto max-h-64">
                        <label className="block mb-2">

                            <div className="flex flex-wrap">
                                {availablePublishers.map(pub => (
                                    <span key={pub.id} className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">{pub.name}</span>
                                ))}
                            </div>
                        </label>
                    </div>
                </div>
                <div className="text-right">
                    <button
                        className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 mr-2"
                        onClick={() => onConfirm(selectedGroups)}
                    >
                        Потвърждавам
                    </button>
                    <button
                        className="bg-gray-300 px-4 py-2 rounded hover:bg-gray-400"
                        onClick={onClose}
                    >
                        Отказ
                    </button>
                </div>
            </div>
        </div>
    );

}


export default SearchReplacement;
