import React, { useState, useEffect } from 'react';
import { classes } from '../../styles/tailwindStyles';
import defaultImage from '../../assets/SharedSVG/Phantom.svg';
import ToggleStatus from '../../helpers/LMS-WildCard-Helpers/UniversalCrud/ToggleStatus';
import { useAuthUser } from 'react-auth-kit';
import HomeCard from './HomeCard';
import { FaClock } from 'react-icons/fa'; 
import ViewLibrary from '../../Library/ViewLibrary';
import { deleteItem } from '../../helpers/LMS-WildCard-Helpers/UniversalCrud/UniversalCrudHelpers';
import { FaTrash } from 'react-icons/fa';
import useIsOwner from '../../helpers/useIsOwner';
import { friendlyTime } from '../../helpers/friendlyTime';
import { AtomSpinner } from 'react-epic-spinners';
const LibraryCard = ({ model, setMode, svg = defaultImage }) => {
    console.log(model)
    const [isPublished, setIsPublished] = useState(model?.public);
    const [isLoading, setIsLoading] = useState(false);

    const handleCardClick = () => {
        // Check if the clicked target is the card itself, not its children
            setMode(<ViewLibrary model={model} setMode={setMode} />);
    };

    const handleTitleClick = (e) => {
        e.stopPropagation();
        // Handle title click - expand details
    };

    const handleToggleChange = (newStatus) => {
        setIsPublished(newStatus);
    };

    useEffect(() => {
        setIsPublished(model?.public);
    }, [model]);

    const glowColor = isPublished ? classes.cardGlowBlue : classes.cardGlowRed;
    const auth = useAuthUser();
    const isOwner = useIsOwner(model?.owner);


        const handleDeleteClick = async (e) => {
        e.stopPropagation();
        const isConfirmed = window.confirm('Are you sure you want to delete this item?');
        if (isConfirmed) {
            handleDelete(e);
        }
    };
 const handleDelete = async (e) => {
        e.stopPropagation();
        setIsLoading(true);  // Start loading animation
        try {
            await deleteItem('Library', model._id, 'LeumasAPI', auth().token);
            // You might want to refresh your library list after deletion or navigate to another page
        } catch (error) {
            console.error("Failed to delete the library:", error);
        } finally {
            setIsLoading(false);  // End loading animation
        }
    };

    
    return (
        <>
   

   {isLoading ? (
            <div className="flex justify-center items-center h-full w-full absolute z-60">
                <AtomSpinner color="blue" />
            </div>
        ) : (
            // ... (rest of your component)
        <>
       
        <div 
            onClick={handleCardClick}
            className={`relative h-full flex flex-col w-200 border-2 p-4 rounded-xl backdrop-blur-md hover:${glowColor} shadow-lg transition-transform transform hover:scale-105 cursor-pointer text-white`}
            style={{
                backgroundImage: `url(${model?.image || svg})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center'
            }}
        >
            <div className="absolute inset-0 bg-black bg-opacity-40 rounded-lg"></div>

            <div className="flex flex-col justify-start mb-2 flex-grow z-10">
                <h2 onClick={handleTitleClick} className="font-bold text-lg hover:text-blue-500 cursor-pointer">{model?.name}</h2>
                <p className="text-sm mt-2 line-clamp-2">{model?.description}</p>
            </div>

            <div className="absolute bottom-2 right-2 flex items-center text-xs z-10">
                <FaClock size={12} className="mr-1" />
                Updated: {friendlyTime(model?.updatedAt)}
            </div>
        </div>

        {auth()?.id && isOwner && (  
            <>
                <div className="absolute bottom-2 left-2 flex items-center z-50">
                    <ToggleStatus 
                        isPublished={isPublished ? isPublished : false} 
                        model="Library" 
                        endpoint="LeumasAPI" 
                        itemId={model._id} 
                        token={auth().token} 
                        onToggleChange={handleToggleChange}
                    />
                </div>
                <div className="absolute top-2 right-2 flex items-center z-50">
                    <button onClick={handleDeleteClick} className="p-1 bg-red-500 rounded hover:bg-red-600">
                        <FaTrash />
                    </button>
                </div>
            </>
        )}  

        </>
 )}
       </>
    );
};

export default LibraryCard;
