import { useState } from '@wordpress/element';
import useEditorStore from '../store/useEditorStore';

export default function TopToolbar() {
    const editingTemplate = useEditorStore((s) => s.editingTemplate);
    const isDirty = useEditorStore((s) => s.isDirty);
    const isSaving = useEditorStore((s) => s.isSaving);
    const devicePreview = useEditorStore((s) => s.devicePreview);
    const historyIndex = useEditorStore((s) => s.historyIndex);
    const history = useEditorStore((s) => s.history);
    const setDevicePreview = useEditorStore((s) => s.setDevicePreview);
    const updateTemplateName = useEditorStore((s) => s.updateTemplateName);
    const exitEditor = useEditorStore((s) => s.exitEditor);
    const undo = useEditorStore((s) => s.undo);
    const redo = useEditorStore((s) => s.redo);
    const saveTemplate = useEditorStore((s) => s.saveTemplate);
    const resetTemplate = useEditorStore((s) => s.resetTemplate);

    const isAdvanced = editingTemplate?.type === 'advanced';

    const [isEditing, setIsEditing] = useState(false);
    const [tempName, setTempName] = useState('');

    const handleBack = () => {
        if (isDirty) {
            if (!window.confirm('You have unsaved changes. Leave anyway?')) {
                return;
            }
        }
        exitEditor();
    };

    const startEditing = () => {
        setTempName(editingTemplate?.name || '');
        setIsEditing(true);
    };

    const finishEditing = () => {
        if (tempName.trim()) {
            updateTemplateName(tempName.trim());
        }
        setIsEditing(false);
    };

    const canUndo = historyIndex > 0;
    const canRedo = historyIndex < history.length - 1;

    return (
        <div className="lpcd-top-toolbar">
            <div className="lpcd-toolbar-left">
                <button className="lpcd-btn lpcd-btn-ghost" onClick={handleBack}>
                    <span className="dashicons dashicons-arrow-left-alt" /> Back
                </button>

                {editingTemplate?.type === 'free' && (
                    <button
                        className="lpcd-btn lpcd-btn-ghost"
                        onClick={() => resetTemplate(editingTemplate.id)}
                        style={{ color: '#dc2626', marginLeft: '8px' }}
                        title="Reset to original design"
                    >
                        <span className="dashicons dashicons-undo" /> Reset
                    </button>
                )}
                {isAdvanced && (
                    <button
                        className="lpcd-btn lpcd-btn-ghost"
                        onClick={() => resetTemplate(editingTemplate.id)}
                        style={{ color: '#dc2626', marginLeft: '8px' }}
                        title="Reset to original design"
                    >
                        <span className="dashicons dashicons-undo" /> Reset
                    </button>
                )}
            </div>

            <div className="lpcd-toolbar-center">
                {isAdvanced ? (
                    <span className="lpcd-template-name-btn" style={{ cursor: 'default' }}>
                        {editingTemplate?.name || 'Untitled'}
                        <span className="lpcd-badge-advanced" style={{ marginLeft: '8px', fontSize: '10px', background: '#7c3aed', color: '#fff', padding: '2px 8px', borderRadius: '10px', fontWeight: '600' }}>ADVANCED</span>
                    </span>
                ) : isEditing ? (
                    <input
                        type="text"
                        className="lpcd-template-name-input"
                        value={tempName}
                        onChange={(e) => setTempName(e.target.value)}
                        onBlur={finishEditing}
                        onKeyDown={(e) => e.key === 'Enter' && finishEditing()}
                        autoFocus
                    />
                ) : (
                    <button
                        className="lpcd-template-name-btn"
                        onClick={startEditing}
                        title="Click to rename"
                    >
                        {editingTemplate?.name || 'Untitled'}
                        <span className="dashicons dashicons-edit" />
                    </button>
                )}
            </div>

            <div className="lpcd-toolbar-right">
                <button
                    className="lpcd-btn lpcd-btn-icon"
                    onClick={undo}
                    disabled={!canUndo}
                    title="Undo"
                >
                    <span className="dashicons dashicons-undo" />
                </button>
                <button
                    className="lpcd-btn lpcd-btn-icon"
                    onClick={redo}
                    disabled={!canRedo}
                    title="Redo"
                >
                    <span className="dashicons dashicons-redo" />
                </button>

                <div className="lpcd-toolbar-divider" />

                <div className="lpcd-device-toggle">
                    {['desktop', 'tablet', 'mobile'].map((device) => (
                        <button
                            key={device}
                            className={`lpcd-device-btn ${devicePreview === device ? 'active' : ''}`}
                            onClick={() => setDevicePreview(device)}
                            title={device.charAt(0).toUpperCase() + device.slice(1)}
                        >
                            <span className={`dashicons dashicons-${device === 'desktop' ? 'desktop' : device === 'tablet' ? 'tablet' : 'smartphone'}`} />
                        </button>
                    ))}
                </div>

                <div className="lpcd-toolbar-divider" />

                <button
                    className="lpcd-btn lpcd-btn-secondary"
                    onClick={() => saveTemplate(false)}
                    disabled={isSaving || !isDirty}
                >
                    {isSaving ? 'Saving...' : 'Save Draft'}
                </button>
                {(() => {
                    const FREE_NAMES = ['Light Centered', 'Dark Centered'];
                    const isProTemplate = editingTemplate && !FREE_NAMES.includes(editingTemplate.name) && editingTemplate.type !== 'custom';
                    const isPro = !!window.lpcdEditor?.isPro;
                    if (isProTemplate && !isPro) {
                        return (
                            <button className="lpcd-btn lpcd-btn-primary" disabled title="Upgrade to Pro to activate this template" style={{ opacity: 0.6 }}>
                                🔒 Upgrade to Activate
                            </button>
                        );
                    }
                    return (
                        <button
                            className="lpcd-btn lpcd-btn-primary"
                            onClick={() => saveTemplate(true)}
                            disabled={isSaving}
                        >
                            {isSaving ? 'Publishing...' : 'Publish & Activate'}
                        </button>
                    );
                })()} 
            </div>
        </div>
    );
}
