// ==========================================
// NotesPane Kit — SaveToNoteDialog
// ==========================================
// "Save to note" dialog: create-new or append-to-existing.
// Independently importable by any surface (ChatPane, etc.).

import { renderNoteMarkdown } from './markdown.js';

const { useState, useRef, useCallback, useEffect } = window.hooks;
const html = window.html;

/**
 * @param {{
 *   open: boolean,
 *   onClose: () => void,
 *   content: string,
 *   sourceChannelId?: string,
 *   sourceMessageId?: string,
 *   defaultTitle?: string,
 * }} props
 */
export function SaveToNoteDialog(props) {
    const { open, onClose, content, sourceChannelId, sourceMessageId, defaultTitle } = props;

    const [mode, setMode] = useState('create'); // 'create' | 'append'
    const [title, setTitle] = useState(defaultTitle || '');
    const [folderPath, setFolderPath] = useState('');
    const [tags, setTags] = useState('');
    const [searchQuery, setSearchQuery] = useState('');
    const [searchResults, setSearchResults] = useState([]);
    const [selectedNote, setSelectedNote] = useState(null);
    const [saving, setSaving] = useState(false);

    const searchTimerRef = useRef(null);
    const titleInputRef = useRef(null);

    // ── Reset on open ───────────────────────
    useEffect(() => {
        if (open) {
            setMode('create');
            setTitle(defaultTitle || '');
            setFolderPath('');
            setTags('');
            setSearchQuery('');
            setSearchResults([]);
            setSelectedNote(null);
            setTimeout(() => titleInputRef.current?.focus(), 50);
        }
    }, [open, defaultTitle]);

    // ── Search for append target ────────────
    useEffect(() => {
        clearTimeout(searchTimerRef.current);
        if (mode !== 'append' || searchQuery.length < 2) {
            setSearchResults([]);
            return;
        }
        searchTimerRef.current = setTimeout(async () => {
            try {
                const resp = await window.sw.api.notes.searchTitles(searchQuery, 8);
                setSearchResults(resp || []);
            } catch { setSearchResults([]); }
        }, 250);
    }, [searchQuery, mode]);

    // ── Save ────────────────────────────────
    const handleSave = useCallback(async () => {
        if (saving) return;
        setSaving(true);
        const api = window.sw.api.notes;
        const toast = window.sw?.toast;

        try {
            if (mode === 'append') {
                if (!selectedNote) {
                    toast?.('Select a note to append to', 'warning');
                    setSaving(false);
                    return;
                }
                await api.update(selectedNote.id, {
                    content: '\n\n---\n\n' + content,
                    mode: 'append',
                });
                toast?.(`Appended to "${selectedNote.title}"`, 'success');
            } else {
                if (!title.trim()) {
                    toast?.('Title is required', 'warning');
                    setSaving(false);
                    return;
                }
                const tagsArr = tags ? tags.split(',').map(t => t.trim()).filter(Boolean) : [];
                await api.create({
                    title: title.trim(),
                    content,
                    folder_path: folderPath.trim(),
                    tags: tagsArr,
                    source_channel_id: sourceChannelId,
                    source_message_id: sourceMessageId,
                });
                toast?.('Note created', 'success');
            }
            onClose();
        } catch (e) {
            toast?.(e.message, 'error');
        }
        setSaving(false);
    }, [mode, title, folderPath, tags, content, selectedNote, sourceChannelId, sourceMessageId, onClose, saving]);

    if (!open) return null;

    // Preview
    const previewContent = content ? content.slice(0, 300) + (content.length > 300 ? '\u2026' : '') : '';
    const { html: previewHtml } = renderNoteMarkdown(previewContent);

    return html`
        <div class="sw-notes-pane__switcher-overlay" onClick=${(e) => { if (e.target === e.currentTarget) onClose(); }}>
            <div class="sw-notes-pane__switcher" style="width:min(480px,90vw)">
                <div style="padding:14px">
                    <h3 style="margin:0 0 10px;font-size:15px;color:var(--text)">Save to Note</h3>

                    <div class="sw-notes-pane__save-mode">
                        <label>
                            <input type="radio" name="saveMode" value="create"
                                   checked=${mode === 'create'}
                                   onChange=${() => setMode('create')} />
                            Create new
                        </label>
                        <label>
                            <input type="radio" name="saveMode" value="append"
                                   checked=${mode === 'append'}
                                   onChange=${() => setMode('append')} />
                            Append to existing
                        </label>
                    </div>

                    ${mode === 'create' && html`
                        <div style="display:flex;flex-direction:column;gap:6px;margin-bottom:10px">
                            <input class="sw-notes-pane__search-input" type="text"
                                   ref=${titleInputRef} placeholder="Title"
                                   value=${title} onInput=${e => setTitle(e.target.value)} />
                            <div style="display:flex;gap:6px">
                                <input class="sw-notes-pane__search-input" type="text"
                                       placeholder="Folder (e.g. /work)" style="flex:1"
                                       value=${folderPath} onInput=${e => setFolderPath(e.target.value)} />
                                <input class="sw-notes-pane__search-input" type="text"
                                       placeholder="Tags (comma-separated)" style="flex:1"
                                       value=${tags} onInput=${e => setTags(e.target.value)} />
                            </div>
                        </div>`}

                    ${mode === 'append' && html`
                        <div style="margin-bottom:10px">
                            <input class="sw-notes-pane__search-input" type="text"
                                   placeholder="Search notes to append to\u2026"
                                   value=${searchQuery}
                                   onInput=${e => setSearchQuery(e.target.value)} />
                            ${searchResults.length > 0 && html`
                                <div class="sw-notes-pane__save-search-results">
                                    ${searchResults.map(n => html`
                                        <div key=${n.id}
                                             class=${'sw-notes-pane__save-search-item' + (selectedNote?.id === n.id ? ' sw-notes-pane__save-search-item--selected' : '')}
                                             onClick=${() => { setSelectedNote(n); setSearchQuery(n.title); }}>
                                            ${n.title}
                                        </div>`)}
                                </div>`}
                        </div>`}

                    <div style="margin-bottom:10px">
                        <div style="font-size:11px;color:var(--text-3);margin-bottom:4px">
                            Preview (${content?.length || 0} chars)
                        </div>
                        <div class="sw-notes-pane__save-preview"
                             dangerouslySetInnerHTML=${{ __html: previewHtml }} />
                    </div>

                    <div style="display:flex;justify-content:flex-end;gap:6px">
                        <button class="sw-notes-pane__toolbar-btn" onClick=${onClose}>Cancel</button>
                        <button class="sw-notes-pane__toolbar-btn"
                                style="color:var(--accent);border-color:var(--accent)"
                                onClick=${handleSave} disabled=${saving}>
                            ${saving ? 'Saving\u2026' : (mode === 'append' ? 'Append' : 'Create')}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
}
