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 - extensible for adding more fonts
const AVAILABLE_FONTS = [
    {
        name: 'Montserrat',
        value: 'Montserrat',
        fontFiles: {
            normal: '/fonts/Montserrat/static/Montserrat-Regular.ttf',
            bold: '/fonts/Montserrat/static/Montserrat-Bold.ttf',
            italic: '/fonts/Montserrat/static/Montserrat-Italic.ttf',
            boldItalic: '/fonts/Montserrat/static/Montserrat-BoldItalic.ttf',
        },
    },
];

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

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

    // Update state when selected element changes - THIS KEEPS SIDEBAR IN SYNC WITH TRANSFORMER
    useEffect(() => {
        if (selectedTextElement) {
            setTextValue(selectedTextElement.text || '');
            setFontSize(selectedTextElement.fontSize || 24); // Always use current fontSize from element
            setIsBold(selectedTextElement.fontWeight === 'bold' || selectedTextElement.fontWeight === 700 || true);
            setIsItalic(selectedTextElement.fontStyle === 'italic' || false);
            setFontFamily(selectedTextElement.fontFamily || 'Montserrat');
        }
    }, [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 size changes - CLAMP AND UPDATE
    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 font family changes
    const handleFontFamilyChange = (newFontFamily) => {
        setFontFamily(newFontFamily);

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

    // 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="max-[140px] w-full 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 text-nowrap"
                                    rows={4}
                                    style={{
                                        fontFamily: fontFamily,
                                        fontSize: `${fontSize * 0.6}px`, // Cap preview size for readability
                                        fontWeight: isBold ? 'bold' : 'normal',
                                        fontStyle: isItalic ? 'italic' : 'normal',
                                    }}
                                />
                            </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}>
                                                <span
                                                    style={{
                                                        fontFamily: font.name,
                                                        fontWeight: isBold ? 'bold' : 'normal',
                                                        fontStyle: isItalic ? 'italic' : 'normal',
                                                    }}
                                                >
                                                    {font.name}
                                                </span>
                                            </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>

                                {/* Note about transformer resize */}
                                <div className="mt-1 text-center text-xs text-blue-600">💡 You can also resize by dragging the corners</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>
    );
}
