import type { Component } from 'solid-js'
import { untracked } from '@wovin/core/mobx'
import { Logger } from 'besonders-logger'
import { debounce } from 'lodash-es'
import { createEffect, createSignal, on, Show } from 'solid-js'
import { deleteAllApplogs } from '../../data/datalog/local-applog-idb'
import { syncState } from '../../ipfs/sync-service'
import { useAppSettings } from '../../ui/app-settings'
import { DeleteWithConfirmDialog } from '../mini-components'
import { pwaReloadFuncSignal, pwaUnregisterFuncSignal, pwaUpdateFuncSignal } from '../PwaReloadPrompt'
import { AgentSettings } from './AgentSettings'

const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO) // eslint-disable-line unused-imports/no-unused-vars

export const AppSettings: Component<{}> = () => {
	DEBUG('Creating <AppSettings>')
	// const thread = useCurrentThread()
	// const agent = useAgent()
	const appSettings = useAppSettings()

	const [syncInterval, setSyncInterval] = createSignal(untracked(() => syncState.syncInterval?.toString() || ''))
	const debouncedUpdateSyncInterval = debounce(() => syncState.syncInterval = syncInterval() ? Number.parseInt(syncInterval()) : 0, 700)
	createEffect(on(() => syncInterval(), () => debouncedUpdateSyncInterval(), { defer: true }))

	const onSelectionChanged = (e) => {
		const blockID = e.target.value
		// TODO some sanity checks that the block exists and .?
		appSettings.update({ homeBlock: blockID })
		DEBUG('set home block', e)
	}

	return (
		<div flex='~ col' gap-4>
			<AgentSettings />

			<sl-card class='card-header' style={{ '--border-colly': '#ffffff77', '--padding': 'var(--sl-spacing-medium)' }}>
				<div slot='header'>
					App Settings
				</div>

				<div flex='~ col' gap-4>
					<div>
						<div mb-0 font-bold>Start page</div>
					</div>

					<sl-select required value={appSettings.startPage} onsl-change={({ target }) => appSettings.update({ startPage: target.value })}>
						<sl-option value='empty-block'>Empty note</sl-option>
						<sl-option value='timeline'>Timeline</sl-option>
						<sl-option value='home-block'>Home block</sl-option>
					</sl-select>

					<div>
						<div mb-0 font-bold>Home Block</div>
					</div>

					<sl-input
						type='string'
						label='Choose your home block (Right click or tap on any bullet to "Copy ID")'
						placeholder='Should never be empty, but this needs to be an entity ID for an existing block'
						value={appSettings.homeBlock}
						onInput={onSelectionChanged}
					/>
					{/* <FilteredBlockSelector filterString={blockFilter} onSelectionChanged={onSelectionChanged} /> */}
					<sl-input
						type='number'
						label='Sync interval (seconds, clear to disable)'
						placeholder='Leave empty to disable auto-sync'
						clearable
						value={syncInterval()}
						onInput={e => setSyncInterval(e.target.value)}
						onsl-clear={() => setSyncInterval('')}
					/>
					<sl-input
						type='number'
						label='Minimum idle time before sync starts'
						value={syncState.minIdle}
						onInput={e => (syncState.minIdle = e.target.value)}
					/>

					<div>
						<div mb-0 font-bold>Autocollapse Settings</div>
						<div mb-2 text-sm opacity-80>
							Control how deeply nested blocks are displayed before being automatically collapsed.
							Higher numbers show more levels.
						</div>
					</div>

					<sl-input
						type='number'
						label='Default autocollapse depth'
						help-text='Depth at which blocks collapse when not focused (default: 2)'
						value={appSettings.autocollapseDepth ?? 2}
						onInput={e => appSettings.update({ autocollapseDepth: Number.parseInt(e.target.value) || 2 })}
						min='0'
						max='12'
					/>

					<sl-input
						type='number'
						label='Focused view autocollapse depth'
						help-text='Depth when viewing a specific block (default: 2)'
						value={appSettings.autocollapseDepthFocussed ?? 2}
						onInput={e => appSettings.update({ autocollapseDepthFocussed: Number.parseInt(e.target.value) || 2 })}
						min='0'
						max='12'
					/>

					<sl-input
						type='number'
						label='Timeline view autocollapse depth'
						help-text='Depth in timeline view (default: 1)'
						value={appSettings.autocollapseDepthTimeline ?? 1}
						onInput={e => appSettings.update({ autocollapseDepthTimeline: Number.parseInt(e.target.value) || 1 })}
						min='0'
						max='12'
					/>

					<sl-input
						type='number'
						label='Timeline smartlist autocollapse depth'
						help-text='Depth for smartlists in timeline view (default: 0 = fully collapsed)'
						value={appSettings.autocollapseDepthTimelineSmartlist ?? 0}
						onInput={e => appSettings.update({ autocollapseDepthTimelineSmartlist: Number.parseInt(e.target.value) || 0 })}
						min='0'
						max='12'
					/>
				</div>
			</sl-card>

			<sl-card class='card-header' style={{ '--border-colly': '#ffffff77', '--padding': 'var(--sl-spacing-medium)' }}>
				<div slot='header'>
					Local App & Data
				</div>

				<div flex='~ col' gap-4>
					<div flex='~ col' gap-2>
						<div font-bold>PWA (locally installed webapp)</div>
						<div flex='~ wrap' gap-2>
							<Show when={pwaReloadFuncSignal()}>
								<sl-button onClick={() => pwaReloadFuncSignal()(false)} size='small'>
									Update PWA (no reload)
								</sl-button>
								<sl-button onClick={() => pwaReloadFuncSignal()(true)} size='small'>
									Update PWA (with reload)
								</sl-button>
							</Show>
							<Show when={pwaUpdateFuncSignal()}>
								<sl-button onClick={() => pwaUpdateFuncSignal()()} size='small'>
									Update (on SW)
								</sl-button>
							</Show>
							<Show when={pwaReloadFuncSignal()}>
								<sl-button onClick={() => pwaUnregisterFuncSignal()()} size='small'>
									Unregister PWA
								</sl-button>
							</Show>
						</div>
					</div>

					<div flex='~ col' gap-2>
						<div font-bold>Database</div>
						<div flex='~ wrap'>
							<DeleteWithConfirmDialog
								label='Delete all applogs'
								dialogLabel='Delete all applogs?'
								dialogText={'This will DELETE ALL APP DATA from this app (on this device),\nand only keep:\n- the agent info & keys\n- subscriptions & publications\n- some settings'}
								certaintySeconds={5}
								handler={async () => {
									await deleteAllApplogs({ sure: 'I am' })
									window.location.reload()
								}}
								size='small'
							/>
						</div>
					</div>
				</div>
			</sl-card>
		</div>
	)
}
