import { useEffect, useRef, useState } from 'react';
import { IoMdClose } from 'react-icons/io';
import { assignStaff, getAdmins } from '../utils/app';
import cookies from 'js-cookie';
import { notify } from '../utils/helper';

const AssignForm = ({ onClose, stream, course_id }) => {
    const [staffList, setStaffList] = useState([]);
    const [selectedStaffs, setSelectedStaffs] = useState([]);
    const formRef = useRef();

    useEffect(() => {
        const fetchStaffs = async () => {
            const staffResponse = await getAdmins(cookies.get('admin'));
            console.log('Staff Response:', staffResponse); // Debug: Check what you get from the server

            if (staffResponse && staffResponse.data) {
                setStaffList(staffResponse.data); // Populate staff list
                console.log('Staff List:', staffResponse.data); // Debug: Inspect the data structure
            }
        };

        fetchStaffs();
    }, []);

    const handleSelectStaff = (event) => {
        const staffId = event.target.value;
        console.log('Selected Staff ID:', staffId); // Debug: Check the selected staff ID
        console.log(staffList, 'staffL:ist')
        const staff = staffList.find(s => s.id == staffId);
        console.log('Selected Staff:', staff); // Debug: See if the staff is found correctly

        if (staff) {
            handleClickAdd(staff);
        } else {
            console.error('Selected staff not found in the staff list.');
        }
    };

    console.log(selectedStaffs, 'selectedStaffs')

    const handleClickAdd = (staff) => {
        if (!selectedStaffs.some(s => s.id === staff.id)) {
            setSelectedStaffs(prev => [...prev, staff]);
        }
    };

    const handleClickCancel = (id) => {
        setSelectedStaffs(prev => prev.filter(staff => staff.id !== id));
    };

    const handleAssignStaff = async (event) => {
        event.preventDefault();

        try {
            const ids = [];

            for (let staff of selectedStaffs) {
                ids.push(staff.id);
            }

            const response = await assignStaff(cookies.get('admin'), stream, course_id, { admin_ids: ids });

            if (!response) throw new Error('Failed to assign course');

            onClose();
        } catch (error) {
            console.log(error)
            if (error.response?.data?.errors) return notify('error', error.response.data.message)
            notify('error', error.message);
        }
    }

    return (
        <div>
            <div className="fixed inset-0 flex items-center justify-center z-50 w-screen p-5 fade-in-regular">
                <div className="fixed inset-0 bg-black opacity-30"></div>
                <div className="relative h-80 w-full max-w-5xl p-3 overflow-hidden bg-white rounded-lg md:p-10">
                    <div className='flex justify-between mb-5'>
                        <h2 className="text-black text-2xl font-bold text-center">Assign</h2>
                        <IoMdClose className="text-xl md:text-3xl cursor-pointer hover:text-red-600" onClick={onClose} />
                    </div>
                    <form ref={formRef} onSubmit={handleAssignStaff}>
                        <div className='flex flex-col mt-5 bg-slate-200 p-1 mb-3 shadow-md min-h-10'>
                            {selectedStaffs.length > 0 && (
                                <div>
                                    <h2 className='text-lg font-bold mb-2 text-black'>Selected Staffs:</h2>
                                    <ul className='flex gap-3 flex-wrap'>
                                        {selectedStaffs.map(staff => (
                                            <li key={staff.id} className='flex items-center justify-between bg-orange-400 w-auto h-10 p-1 mb-2 rounded-md'>
                                                <span className='text-white'>{staff.name}</span>
                                                <IoMdClose onClick={() => handleClickCancel(staff.id)} className='cursor-pointer text-black' />
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            )}
                        </div>
                        <div className="flex flex-col gap-5">
                            <select className="bg-orange-500 text-white rounded-lg h-12 p-2 w-full" onChange={handleSelectStaff}>
                                <option value="">Select Staff</option>
                                {staffList.map((staff) => (
                                    <option key={staff.id} value={staff.id}>{staff.name}</option>
                                ))}
                            </select>
                        </div>

                        <button type='submit' className="text-white bg-orange-700 w-32 h-10 rounded-md absolute bottom-5 right-10 mt-5" disabled={selectedStaffs.length < 1}>Upload</button>
                    </form>
                </div>
            </div>
        </div>
    )
}

export default AssignForm;




// import { useEffect, useRef, useState } from 'react'
// import { IoMdClose } from 'react-icons/io'
// import { getProgrammes } from '../utils/app';
// import cookies from 'js-cookie';

// const AssignForm = ({ onClose }) => {
//     const [programmes, setProgrammes] = useState([]);
//     const formRef = useRef();
//     const [selectedStaffs, setSelectedStaffs] = useState([]);


//     const handleClickAdd = (staff) => {
//         if (!selectedStaffs.find(c => c.id === staff.id)) {
//             setSelectedStaffs((prev) => [...prev, staff]);
//         }
//     };

//     const handleClickCancel = (id) => {
//         setSelectedStaffs((prev) =>
//             prev.filter((staff) => staff.id !== id)
//         )
//     };

//     // useEffect(() => {
//     //     const fetchProgrammes = async () => {
//     //         const programmes = await getProgrammes(cookies.get('admin'));

//     //         if (!programmes) return;

//     //         setProgrammes(programmes.data);
//     //     }

//     //     fetchProgrammes();
//     // }, []);


//     return (
//         <div>
//             <div className="fixed inset-0 flex items-center justify-center z-50 w-screen p-5 fade-in-regular">
//                 <div className="fixed inset-0 bg-black opacity-30"></div>
//                 <div className="relative h-80 w-full max-w-5xl p-3 overflow-hidden bg-white rounded-lg md:p-10">
//                     <div className='flex justify-between mb-5'>
//                         <h2 className="text-black text-2xl font-bold text-center">Assign</h2>
//                         <div className="flex justify-end w-full">
//                             <IoMdClose
//                                 className="mb-3 text-xl transition duration-300 ease-in-out cursor-pointer md:text-3xl md:mb-0 text-slate-800 hover:text-red-600"
//                                 onClick={onClose}
//                             />
//                         </div>

//                     </div>
//                     <form ref={formRef}>
//                         <div className='flex flex-col mt-5 bg-slate-200 p-1 mb-3 shadow-md min-h-10'>
//                             {selectedStaffs.length > 0 && (
//                                 <div className=''>
//                                     <h2 className='text-lg font-bold mb-2 text-black'>Selected Staffs:</h2>
//                                     <ul className='flex gap-3'>
//                                         {selectedStaffs.map(staff => (
//                                             <li key={staff.id} className='flex items-center justify-between bg-orange-400 w-32 h-10 p-1 mb-2 rounded-md'>
//                                                 <span className='text-white'>{staff.code}</span>
//                                                 <IoMdClose onClick={() => handleClickCancel(staff.id)} className='cursor-pointer text-black' />
//                                             </li>
//                                         ))}
//                                     </ul>
//                                     <button className='text-right border-orange-400 text-orange-500' onClick={handleRegister}>Continue</button>
//                                 </div>
//                             )}
//                         </div>
//                         <div className="flex flex-col gap-5">
//                             <select className="bg-orange-500 text-white placeholder:text-white outline-none rounded-lg h-12 p-2 w-full" name="session_id">
//                                 <option>programme</option>
//                                 {programmes.map((prog, i) => (
//                                     <option key={i} value={prog.id}>{prog.name} - {prog.stream}</option>
//                                 ))}
//                             </select>
//                         </div>
//                         <button className="text-white bg-orange-700 w-32 h-10 rounded-md absolute bottom-5 right-10 mt-5" disabled>Upload</button>
//                     </form>
//                 </div>
//             </div>
//         </div>
//     )
// }

// export default AssignForm