import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';
import { useMitt } from '@/plugins/MittContext';
import useVideoEditorStore from '@/stores/VideoEditorStore';
import { Type } from 'lucide-react';
import { useEffect, useState } from 'react';

export default function TextSidebar({ isOpen, onClose }) {
    const { selectedTextElement } = useVideoEditorStore();
    const emitter = useMitt();
    const [textValue, setTextValue] = useState('');

    // Update textarea when selected element changes
    useEffect(() => {
        if (selectedTextElement) {
            setTextValue(selectedTextElement.text || '');
        }
    }, [selectedTextElement]);

    // Handle text changes
    const handleTextChange = (e) => {
        const newText = e.target.value;
        setTextValue(newText);

        if (selectedTextElement) {
            emitter.emit('text-update', {
                elementId: selectedTextElement.id,
                updates: { text: newText },
            });
        }
    };

    return (
        <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <SheetContent side="right" className="w-80 overflow-y-auto">
                <SheetHeader>
                    <SheetTitle className="flex items-center gap-3">
                        <Type className="h-6 w-6" />
                        Edit Text
                    </SheetTitle>
                </SheetHeader>

                <div className="mt-6 space-y-4 px-2">
                    {selectedTextElement ? (
                        <>
                            <div>
                                <label className="text-sm font-medium">Edit your text here</label>
                                <Textarea
                                    value={textValue}
                                    onChange={handleTextChange}
                                    placeholder="Enter your text..."
                                    className="mt-2 text-center"
                                    rows={4}
                                />
                            </div>
                        </>
                    ) : (
                        <div className="text-center text-gray-500">
                            <Type className="mx-auto h-12 w-12 text-gray-300" />
                            <p className="mt-2">Select a text element to edit</p>
                        </div>
                    )}
                </div>
            </SheetContent>
        </Sheet>
    );
}
