import { useState, useEffect, useCallback } from 'react'
import { MizanProvider, useMizan, useMizanStatus } from '@rythazhur/mizan'

// ─── System Info ────────────────────────────────────────────────────────────

function SystemInfo() {
    const { call } = useMizan()
    const [info, setInfo] = useState<Record<string, unknown> | null>(null)

    useEffect(() => {
        call('system_info').then(setInfo).catch(() => {})
    }, [call])

    if (!info) return <div style={styles.card}>Loading system info...</div>

    return (
        <div style={styles.card}>
            <h2 style={styles.h2}>System</h2>
            <table style={styles.table}>
                <tbody>
                    {Object.entries(info).map(([k, v]) => (
                        <tr key={k}>
                            <td style={styles.label}>{k}</td>
                            <td style={styles.value}>{String(v)}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    )
}

// ─── Connection Status ──────────────────────────────────────────────────────

function StatusBar() {
    const status = useMizanStatus()
    return (
        <div style={{ ...styles.statusBar, color: status === 'connected' ? '#4ade80' : '#f87171' }}>
            {status}
        </div>
    )
}

// ─── Notes ──────────────────────────────────────────────────────────────────

type Note = { id: number; title: string; content: string; pinned: boolean; updated_at: string }

function Notes() {
    const { call } = useMizan()
    const [notes, setNotes] = useState<Note[]>([])
    const [selected, setSelected] = useState<Note | null>(null)
    const [title, setTitle] = useState('')
    const [content, setContent] = useState('')

    const refresh = useCallback(() => {
        call<{ notes: Note[] }>('list_notes').then(d => setNotes(d.notes)).catch(() => {})
    }, [call])

    useEffect(() => { refresh() }, [refresh])

    const create = async () => {
        if (!title.trim()) return
        await call('create_note', { title, content })
        setTitle('')
        setContent('')
        refresh()
    }

    const save = async () => {
        if (!selected) return
        await call('update_note', { id: selected.id, title, content })
        setSelected(null)
        setTitle('')
        setContent('')
        refresh()
    }

    const remove = async (id: number) => {
        await call('delete_note', { id })
        if (selected?.id === id) { setSelected(null); setTitle(''); setContent('') }
        refresh()
    }

    const select = (n: Note) => {
        setSelected(n)
        setTitle(n.title)
        setContent(n.content)
    }

    return (
        <div style={styles.card}>
            <h2 style={styles.h2}>Notes ({notes.length})</h2>
            <div style={{ display: 'flex', gap: 12 }}>
                <div style={{ flex: 1 }}>
                    {notes.map(n => (
                        <div
                            key={n.id}
                            onClick={() => select(n)}
                            style={{
                                ...styles.noteItem,
                                borderLeft: selected?.id === n.id ? '3px solid #6cf' : '3px solid transparent',
                            }}
                        >
                            <span>{n.pinned ? '\u{1f4cc} ' : ''}{n.title}</span>
                            <button onClick={e => { e.stopPropagation(); remove(n.id) }} style={styles.deleteBtn}>x</button>
                        </div>
                    ))}
                    {notes.length === 0 && <div style={{ color: '#666', padding: 8 }}>No notes yet</div>}
                </div>
                <div style={{ flex: 2 }}>
                    <input
                        value={title}
                        onChange={e => setTitle(e.target.value)}
                        placeholder="Title"
                        style={styles.input}
                    />
                    <textarea
                        value={content}
                        onChange={e => setContent(e.target.value)}
                        placeholder="Content"
                        rows={6}
                        style={{ ...styles.input, resize: 'vertical' }}
                    />
                    <button onClick={selected ? save : create} style={styles.btn}>
                        {selected ? 'Save' : 'Create'}
                    </button>
                    {selected && (
                        <button onClick={() => { setSelected(null); setTitle(''); setContent('') }} style={{ ...styles.btn, background: '#333' }}>
                            Cancel
                        </button>
                    )}
                </div>
            </div>
        </div>
    )
}

// ─── File Browser ───────────────────────────────────────────────────────────

type FileEntry = { name: string; path: string; is_dir: boolean; size: number }

function FileBrowser() {
    const { call } = useMizan()
    const [dir, setDir] = useState('~')
    const [entries, setEntries] = useState<FileEntry[]>([])
    const [parent, setParent] = useState<string | null>(null)

    const browse = useCallback((d: string) => {
        call<{ directory: string; entries: FileEntry[]; parent: string | null }>('list_files', { directory: d })
            .then(data => {
                setDir(data.directory)
                setEntries(data.entries.slice(0, 50))
                setParent(data.parent)
            })
            .catch(() => {})
    }, [call])

    useEffect(() => { browse('~') }, [browse])

    return (
        <div style={styles.card}>
            <h2 style={styles.h2}>Files</h2>
            <div style={{ color: '#888', fontSize: 13, marginBottom: 8 }}>{dir}</div>
            {parent && (
                <div onClick={() => browse(parent)} style={{ ...styles.fileItem, color: '#6cf', cursor: 'pointer' }}>
                    ../ (parent)
                </div>
            )}
            {entries.map(e => (
                <div
                    key={e.path}
                    onClick={() => e.is_dir && browse(e.path)}
                    style={{ ...styles.fileItem, cursor: e.is_dir ? 'pointer' : 'default', color: e.is_dir ? '#6cf' : '#ccc' }}
                >
                    {e.is_dir ? '\u{1f4c1}' : '\u{1f4c4}'} {e.name}
                    {!e.is_dir && <span style={{ color: '#666', marginLeft: 8 }}>{(e.size / 1024).toFixed(1)}K</span>}
                </div>
            ))}
        </div>
    )
}

// ─── App ────────────────────────────────────────────────────────────────────

export function App() {
    return (
        <MizanProvider baseUrl="/api/mizan" autoConnect={false}>
            <div style={{ maxWidth: 960, margin: '0 auto', padding: 24 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
                    <h1 style={{ fontSize: 24, color: '#fff' }}>mizan Desktop</h1>
                    <StatusBar />
                </div>
                <SystemInfo />
                <Notes />
                <FileBrowser />
            </div>
        </MizanProvider>
    )
}

// ─── Styles ─────────────────────────────────────────────────────────────────

const styles: Record<string, React.CSSProperties> = {
    card: { background: '#1a1a1a', borderRadius: 8, padding: 20, marginBottom: 16 },
    h2: { fontSize: 16, marginBottom: 12, color: '#aaa', textTransform: 'uppercase', letterSpacing: 1 },
    table: { width: '100%', fontSize: 14 },
    label: { padding: '4px 12px 4px 0', color: '#888', whiteSpace: 'nowrap' },
    value: { padding: '4px 0', wordBreak: 'break-all' },
    input: { width: '100%', padding: '8px 12px', marginBottom: 8, background: '#111', border: '1px solid #333', borderRadius: 4, color: '#e0e0e0', fontSize: 14 },
    btn: { padding: '8px 16px', background: '#2563eb', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer', marginRight: 8, fontSize: 14 },
    noteItem: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', cursor: 'pointer', borderRadius: 4, marginBottom: 2 },
    deleteBtn: { background: 'none', border: 'none', color: '#666', cursor: 'pointer', fontSize: 14, padding: '2px 6px' },
    fileItem: { padding: '4px 8px', fontSize: 14 },
    statusBar: { fontSize: 12, fontFamily: 'monospace' },
}
