import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
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 { Bold, Italic, Minus, Plus, Type } from 'lucide-react';
import { useEffect, useState } from 'react';

// Font configuration
const DEFAULT_FONT_FAMILY = 'Montserrat';
const AVAILABLE_FONTS = [{ value: 'Montserrat', label: 'Montserrat' }];

export default function TextSidebar({ isOpen, onClose }) {
    const { selectedTextElement } = useVideoEditorStore();
    const emitter = useMitt();
    const [textValue, setTextValue] = useState('');
    const [fontSize, setFontSize] = useState(24);
    const [fontFamily, setFontFamily] = useState(DEFAULT_FONT_FAMILY);
    const [isBold, setIsBold] = useState(true);
    const [isItalic, setIsItalic] = useState(false);

    // Font size constraints
    const MIN_FONT_SIZE = 8;
    const MAX_FONT_SIZE = 120;
    const FONT_SIZE_STEP = 2;

    // Update all state when selected element changes
    useEffect(() => {
        if (selectedTextElement) {
            setTextValue(selectedTextElement.text || '');
            setFontSize(selectedTextElement.fontSize || 24);
            setFontFamily(selectedTextElement.fontFamily || DEFAULT_FONT_FAMILY);
            setIsBold(selectedTextElement.fontWeight === 'bold' || selectedTextElement.fontWeight === 700 || true);
            setIsItalic(selectedTextElement.fontStyle === 'italic' || false);
        }
    }, [selectedTextElement]);

    // Listen for fontSize changes from canvas transformations (separate from selection)
    useEffect(() => {
        const handleTextElementUpdate = (updatedElement) => {
            if (selectedTextElement && updatedElement.id === selectedTextElement.id) {
                // Update local state to reflect changes from canvas
                if (updatedElement.fontSize !== undefined) {
                    setFontSize(updatedElement.fontSize);
                }
                if (updatedElement.text !== undefined) {
                    setTextValue(updatedElement.text);
                }
                if (updatedElement.fontFamily !== undefined) {
                    setFontFamily(updatedElement.fontFamily);
                }
                if (updatedElement.fontWeight !== undefined) {
                    setIsBold(updatedElement.fontWeight === 'bold' || updatedElement.fontWeight === 700);
                }
                if (updatedElement.fontStyle !== undefined) {
                    setIsItalic(updatedElement.fontStyle === 'italic');
                }
            }
        };

        // Listen for updates from canvas transforms (doesn't open sidebar)
        emitter.on('text-element-updated', handleTextElementUpdate);

        return () => {
            emitter.off('text-element-updated', handleTextElementUpdate);
        };
    }, [emitter, 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 },
            });
        }
    };

    // Handle font family changes
    const handleFontFamilyChange = (newFontFamily) => {
        setFontFamily(newFontFamily);

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

    // Handle font size changes
    const handleFontSizeChange = (newSize) => {
        const clampedSize = Math.max(MIN_FONT_SIZE, Math.min(MAX_FONT_SIZE, newSize));
        setFontSize(clampedSize);

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

    // Handle bold toggle
    const handleBoldToggle = () => {
        const newBoldState = !isBold;
        setIsBold(newBoldState);

        if (selectedTextElement) {
            emitter.emit('text-update', {
                elementId: selectedTextElement.id,
                updates: { fontWeight: newBoldState ? 'bold' : 'normal' },
            });
        }
    };

    // Handle italic toggle
    const handleItalicToggle = () => {
        const newItalicState = !isItalic;
        setIsItalic(newItalicState);

        if (selectedTextElement) {
            emitter.emit('text-update', {
                elementId: selectedTextElement.id,
                updates: { fontStyle: newItalicState ? 'italic' : 'normal' },
            });
        }
    };

    // Increase font size
    const increaseFontSize = () => {
        handleFontSizeChange(fontSize + FONT_SIZE_STEP);
    };

    // Decrease font size
    const decreaseFontSize = () => {
        handleFontSizeChange(fontSize - FONT_SIZE_STEP);
    };

    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 ? (
                        <>
                            {/* Text Content */}
                            <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>

                            {/* Font Family */}
                            <div>
                                <label className="text-sm font-medium">Font Family</label>
                                <Select value={fontFamily} onValueChange={handleFontFamilyChange}>
                                    <SelectTrigger className="mt-2">
                                        <SelectValue placeholder="Select font" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {AVAILABLE_FONTS.map((font) => (
                                            <SelectItem key={font.value} value={font.value}>
                                                {font.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Font Size Controls */}
                            <div>
                                <label className="text-sm font-medium">Font Size</label>
                                <div className="mt-2 flex items-center justify-between rounded-lg border p-2">
                                    <Button
                                        variant="outline"
                                        size="icon"
                                        onClick={decreaseFontSize}
                                        disabled={fontSize <= MIN_FONT_SIZE}
                                        className="h-8 w-8"
                                    >
                                        <Minus className="h-4 w-4" />
                                    </Button>

                                    <div className="flex items-center gap-2">
                                        <span className="text-lg font-semibold">{fontSize}</span>
                                        <span className="text-sm text-gray-500">px</span>
                                    </div>

                                    <Button
                                        variant="outline"
                                        size="icon"
                                        onClick={increaseFontSize}
                                        disabled={fontSize >= MAX_FONT_SIZE}
                                        className="h-8 w-8"
                                    >
                                        <Plus className="h-4 w-4" />
                                    </Button>
                                </div>

                                {/* Font Size Range Indicator */}
                                <div className="mt-1 text-center text-xs text-gray-500">
                                    Size range: {MIN_FONT_SIZE}px - {MAX_FONT_SIZE}px
                                </div>

                                {/* Visual feedback for canvas scaling */}
                                <div className="mt-1 text-center text-xs text-blue-600">
                                    💡 Tip: You can also resize text by dragging the corners on the canvas
                                </div>
                            </div>

                            {/* Font Style Controls */}
                            <div>
                                <label className="text-sm font-medium">Font Style</label>
                                <div className="mt-2 flex gap-2">
                                    <Button
                                        variant={isBold ? 'default' : 'outline'}
                                        size="sm"
                                        onClick={handleBoldToggle}
                                        className="flex flex-1 items-center gap-2"
                                    >
                                        <Bold className="h-4 w-4" />
                                        <span className={isBold ? 'font-bold' : 'font-normal'}>Bold</span>
                                    </Button>

                                    <Button
                                        variant={isItalic ? 'default' : 'outline'}
                                        size="sm"
                                        onClick={handleItalicToggle}
                                        className="flex flex-1 items-center gap-2"
                                    >
                                        <Italic className="h-4 w-4" />
                                        <span className={isItalic ? 'italic' : 'not-italic'}>Italic</span>
                                    </Button>
                                </div>
                            </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>
    );
}
