import React, { useState, useEffect } from 'react';
import { getItemById, deleteItem } from '../../helpers/LMS-WildCard-Helpers/UniversalCrud/UniversalCrudHelpers';
import defaultSVG from '../../assets/SharedSVG/AI.svg';
import ToggleStatus from '../../helpers/LMS-WildCard-Helpers/UniversalCrud/ToggleStatus';
import { useAuthUser } from 'react-auth-kit';
import { FaClock, FaTrash } from 'react-icons/fa'; 
import ViewCategory from '../../Library/ViewCategory';
import useIsOwner from '../../helpers/useIsOwner';
import { friendlyTime } from '../../helpers/friendlyTime';
const CategoryCard = ({ model, setMode, svg = defaultSVG }) => {
    const [details, setDetails] = useState(null);
    const [isPublished, setIsPublished] = useState(details?.public);
    const auth = useAuthUser();
    const isOwner = useIsOwner(details?.owner)
    useEffect(() => {
        if (model) {
            getItemById("Category", model, "LeumasAPI", auth()?.token)
                .then(data => {
                    setDetails(data);
                })
                .catch(error => {
                    console.error("Error fetching category details:", error);
                });
        }
    }, [model]);

    useEffect(() => {
        setIsPublished(model?.public);
    }, [model]);

    const glowColor = model?.public ? 'border-blue-500' : 'border-red-500';

    const handleClick = (e) => {
        e.stopPropagation();
        setMode(<ViewCategory model={model} setMode={setMode} />);
    };

    const handleTitleClick = (e) => {
        e.stopPropagation();
        // Handle title click - maybe expand details or navigate to category details
    };

    const handleToggleChange = (newStatus) => {
        setIsPublished(newStatus);
    };

    const handleDeleteClick = async (e) => {
        e.stopPropagation();
        const isConfirmed = window.confirm('Are you sure you want to delete this category and all associated library items?');
        
        if (isConfirmed) {
            const libraryItemsIds = details?.libraryItems;
    
            // Delete each library item associated with the category
            for (let itemId of libraryItemsIds) {
                try {
                 const deletedItem =  await deleteItem('LibraryItem', itemId, 'LeumasAPI', auth().token);
                 console.log(deletedItem)
                } catch (error) {
                    console.error(`Failed to delete library item with ID ${itemId}:`, error);
                }
            }
    
            // Delete the category itself
            try {
                await deleteItem('Category', model, 'LeumasAPI', auth().token);
                // Refresh the category list or navigate after deletion.
            } catch (error) {
                console.error("Failed to delete the category:", error);
            }
        }
    };
    


    return (
        <div className="relative w-200 h-full flex flex-col justify-between rounded-xl overflow-hidden">
            <div 
                onClick={handleClick}
                className={`h-full relative flex flex-col w-full 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(${details?.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 z-10"
                    >
                        {details?.name}
                    </h2>
                    <p className="text-sm mt-2 line-clamp-2">{details?.libraryItems?.length || 0} library items</p>
                </div>
    
                <div className="absolute bottom-2 right-2 flex items-center text-xs z-10">
                    <FaClock size={12} className="mr-1" />
                    Updated: {friendlyTime(details?.updatedAt)}
                </div>
            </div>
    
            {auth()?.id && isOwner && (  // Consider using a condition to check if the current user is the owner.
                <>
                    <div className="absolute bottom-2 left-2 flex items-center z-50">
                        <ToggleStatus 
                            isPublished={details?.public} 
                            model="Category" 
                            endpoint="LeumasAPI" 
                            itemId={details?._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>
                </>
            )}
        </div>
    );
    
    
}

export default CategoryCard;
