import ActiveObjectContext from '@/components/Context/activeObject/ObjectContext';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useContext, useEffect, useRef, useState } from 'react'
import { Card, } from '@/components/ui/card';
import CanvasContext from '@/components/Context/canvasContext/CanvasContext';
import { Separator } from '@/components/ui/separator';
import { fabric } from 'fabric';

const SelectObjectFromGroup = () => {
    const [groupObjects, setGroupObjects] = useState([])
    const [selectedObject, setSelectedObject] = useState(null)
    const { setActiveObject } = useContext(ActiveObjectContext)
    const { canvas } = useContext(CanvasContext)
    const previewCanvasRef = useRef(null)

    const activeObject = canvas?.getActiveObject()

    useEffect(() => {
        if (activeObject?.type === 'group') {
            setGroupObjects(activeObject._objects || [])
            setSelectedObject(null)
        } else {
            setGroupObjects([])
            setSelectedObject(null)
        }
    }, [activeObject])

    // useEffect(() => {
    //     if (selectedObject && previewCanvasRef.current) {
    //         const previewCanvas = new fabric.StaticCanvas(previewCanvasRef.current);

    //         previewCanvas.setDimensions({
    //             width: 100,
    //             height: 100
    //         })

    //         // Clone the active object to create a true deep copy
    //         selectedObject.clone((clonedObject) => {
    //             if (selectedObject?.width > 100 || selectedObject?.height > 100) {
    //                 clonedObject.set({
    //                     scaleX: 0.2,
    //                     scaleY: 0.2,
    //                 })
    //             }
    //             // Add the cloned object to the canvas
    //             clonedObject.set({
    //                 left: 50,
    //                 top: 50,
    //                 originX: 'center',
    //                 originY: 'center',
    //                 selectable: false,
    //                 evented: false,
    //             })
    //             previewCanvas.add(clonedObject);
    //             previewCanvas.renderAll();
    //         });

    //         return () => {
    //             previewCanvas.dispose()
    //         }
    //     }
    // }, [selectedObject])


    useEffect(() => {
        if (selectedObject && previewCanvasRef.current) {
            // Create a new static canvas
            const previewCanvas = new fabric.StaticCanvas(previewCanvasRef.current);

            previewCanvas.setDimensions({
                width: 100,
                height: 100
            });

            // Clear previous objects (if any)
            previewCanvas.clear();

            // Clone the active object for preview
            selectedObject.clone((clonedObject) => {
                const scaledWidth = selectedObject.width * selectedObject.scaleX;
                const scaledHeight = selectedObject.height * selectedObject.scaleY;

                if (scaledWidth > 100 || scaledHeight > 100) {
                    clonedObject.scaleToWidth(100); // Scale to fit width
                    clonedObject.scaleToHeight(100); // Scale to fit height
                }

                clonedObject.set({
                    left: 50,
                    top: 50,
                    originX: 'center',
                    originY: 'center',
                });

                // Add the cloned object to preview canvas
                previewCanvas.add(clonedObject);
                previewCanvas.renderAll();
            });

            // Cleanup function to dispose of the canvas
            return () => {
                previewCanvas.clear();  // Clear all objects
                previewCanvas.dispose(); // Properly dispose the canvas
            };
        }
    }, [selectedObject, previewCanvasRef]);


    const handleSelectObject = (value) => {
        const selected = groupObjects[parseInt(value)]
        setSelectedObject(selected)
        setActiveObject(selected)
    }

    if (!activeObject || activeObject.type !== 'group') {
        return null
    }

    return (
        <div>
            <Card className="p-4">
                <h2 className='font-bold mb-4'>Group Objects</h2>
                <div className='flex flex-col items-center justify-center space-y-4'>
                    <Select
                        onValueChange={handleSelectObject}
                        value={selectedObject ? groupObjects.indexOf(selectedObject).toString() : undefined}
                    >
                        <SelectTrigger className="w-full max-w-xs">
                            <SelectValue placeholder="Select object" />
                        </SelectTrigger>
                        <SelectContent className="max-h-[250px]">
                            {groupObjects.map((object, index) => (
                                <SelectItem key={index} value={index.toString()}>
                                    {object.name || `Object ${index + 1}`}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>

                    {selectedObject && (
                        <div className='w-[100px] h-[100px] bg-muted rounded-md overflow-hidden border border-gray-300'>
                            <canvas ref={previewCanvasRef} width={100} height={100} />
                        </div>
                    )}
                </div>
            </Card>
            <Separator className="my-4" />
        </div>
    )
}
export default SelectObjectFromGroup;