<template>
	<view class="page">
		<view class="toolbar">
			<view class="search-bar">
				<FaIcon name="magnifying-glass" color="#909399" :size="16" />
				<input
					class="search-input"
					v-model="keyword"
					type="text"
					placeholder="搜索笔记标题或内容"
					placeholder-class="search-placeholder"
					confirm-type="search"
					@confirm="loadNotes"
				/>
				<view v-if="keyword" class="search-clear" @tap="clearSearch">
					<FaIcon name="circle-xmark" color="#c0c4cc" :size="16" />
				</view>
			</view>
			<view class="stats-row">
				<text class="stats-text">共 {{ total }} 条</text>
				<text v-if="pinnedCount" class="stats-text">置顶 {{ pinnedCount }} 条</text>
			</view>
		</view>

		<scroll-view class="list-scroll" scroll-y :show-scrollbar="false">
			<view v-if="loading" class="state-box">
				<text class="state-text">加载中...</text>
			</view>
			<view v-else-if="notes.length === 0" class="state-box">
				<FaIcon name="note-sticky" color="#c0c4cc" :size="40" />
				<text class="state-text">{{ keyword ? '未找到相关笔记' : '暂无笔记，点击右下角新建' }}</text>
			</view>
			<view v-else class="note-list">
				<view
					v-for="item in notes"
					:key="item.id"
					class="note-card"
					@tap="openEdit(item.id)"
				>
					<view class="note-head">
						<view class="note-title-row">
							<text v-if="item.pinned" class="pin-tag">置顶</text>
							<text class="note-title">{{ item.title }}</text>
						</view>
						<text class="note-time">{{ formatRelativeTime(item.updatedAt) }}</text>
					</view>
					<text class="note-preview">{{ preview(item.content) }}</text>
					<view class="note-actions" @tap.stop>
						<view class="action-btn" @tap="onTogglePin(item)">
							<FaIcon :name="item.pinned ? 'thumbtack' : 'thumbtack'" :color="item.pinned ? '#3c9cff' : '#909399'" :size="14" />
							<text>{{ item.pinned ? '取消置顶' : '置顶' }}</text>
						</view>
						<view class="action-btn danger" @tap="onDelete(item)">
							<FaIcon name="trash-can" color="#f56c6c" :size="14" />
							<text>删除</text>
						</view>
					</view>
				</view>
			</view>
			<view class="bottom-space" />
		</scroll-view>

		<view class="fab" @tap="createNote">
			<FaIcon name="plus" color="#ffffff" :size="22" />
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { fetchNotes, deleteNote, toggleNotePin } from '@/api/note.js'
import { formatRelativeTime } from '@/utils/date.js'
import { isLoggedIn } from '@/utils/auth.js'

const keyword = ref('')
const notes = ref([])
const total = ref(0)
const loading = ref(false)

const pinnedCount = computed(() => notes.value.filter(item => item.pinned).length)

onMounted(() => {
	if (!isLoggedIn()) {
		uni.reLaunch({ url: '/pages/login/login' })
		return
	}
	loadNotes()
})

onShow(() => {
	if (isLoggedIn()) loadNotes()
})

async function loadNotes() {
	loading.value = true
	try {
		const res = await fetchNotes({ keyword: keyword.value })
		notes.value = res.list
		total.value = res.total
	} catch (e) {
		uni.showToast({ title: '加载失败', icon: 'none' })
	} finally {
		loading.value = false
	}
}

function clearSearch() {
	keyword.value = ''
	loadNotes()
}

function preview(content) {
	const text = (content || '').replace(/\s+/g, ' ').trim()
	if (!text) return '暂无内容'
	return text.length > 60 ? `${text.slice(0, 60)}...` : text
}

function createNote() {
	uni.navigateTo({ url: '/pages/tools/notepad/edit' })
}

function openEdit(id) {
	uni.navigateTo({ url: `/pages/tools/notepad/edit?id=${id}` })
}

async function onTogglePin(item) {
	try {
		await toggleNotePin(item.id)
		await loadNotes()
		uni.showToast({ title: item.pinned ? '已取消置顶' : '已置顶', icon: 'none' })
	} catch (e) {
		uni.showToast({ title: '操作失败', icon: 'none' })
	}
}

function onDelete(item) {
	uni.showModal({
		title: '删除笔记',
		content: `确定删除「${item.title}」吗？`,
		success: async (res) => {
			if (!res.confirm) return
			try {
				await deleteNote(item.id)
				await loadNotes()
				uni.showToast({ title: '已删除', icon: 'none' })
			} catch (e) {
				uni.showToast({ title: '删除失败', icon: 'none' })
			}
		}
	})
}
</script>

<style lang="scss" scoped>
@import '@/src/styles/page-common.scss';

.page {
	min-height: 100vh;
	background: $color-bg-page;
	display: flex;
	flex-direction: column;
}

.toolbar {
	flex-shrink: 0;
	padding: 20rpx $page-padding-x 0;
	background: $color-card;
	box-shadow: $shadow-header;
}

.search-bar {
	display: flex;
	align-items: center;
	gap: 12rpx;
	height: 72rpx;
	padding: 0 24rpx;
	background: $color-bg-page;
	border-radius: $radius-full;
}

.search-input {
	flex: 1;
	height: 72rpx;
	font-size: 28rpx;
	color: $color-text;
}

.search-placeholder {
	color: $color-text-muted;
	font-size: 28rpx;
}

.search-clear {
	display: flex;
	padding: 8rpx;
}

.stats-row {
	display: flex;
	gap: 24rpx;
	padding: 16rpx 4rpx 20rpx;
}

.stats-text {
	font-size: 24rpx;
	color: $color-text-muted;
}

.list-scroll {
	flex: 1;
	height: 0;
}

.note-list {
	padding: 24rpx $page-padding-x 0;
}

.note-card {
	@include card;
	padding: 28rpx 24rpx;
	margin-bottom: 20rpx;

	&:active {
		opacity: 0.92;
	}
}

.note-head {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	gap: 16rpx;
	margin-bottom: 12rpx;
}

.note-title-row {
	flex: 1;
	min-width: 0;
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.pin-tag {
	flex-shrink: 0;
	font-size: 20rpx;
	color: $color-primary;
	background: $color-primary-bg;
	padding: 2rpx 10rpx;
	border-radius: $radius-sm;
}

.note-title {
	font-size: 30rpx;
	font-weight: 600;
	color: $color-text;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.note-time {
	flex-shrink: 0;
	font-size: 22rpx;
	color: $color-text-muted;
}

.note-preview {
	display: block;
	font-size: 26rpx;
	color: $color-text-secondary;
	line-height: 1.6;
	margin-bottom: 20rpx;
}

.note-actions {
	display: flex;
	gap: 24rpx;
	padding-top: 16rpx;
	border-top: 1rpx solid $color-divider;
}

.action-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	font-size: 24rpx;
	color: $color-text-muted;

	&.danger {
		color: #f56c6c;
	}
}

.state-box {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 160rpx 48rpx;
	gap: 20rpx;
}

.state-text {
	font-size: 26rpx;
	color: $color-text-muted;
	text-align: center;
}

.fab {
	position: fixed;
	right: 40rpx;
	bottom: calc(40rpx + env(safe-area-inset-bottom));
	width: 104rpx;
	height: 104rpx;
	border-radius: 50%;
	background: $color-primary;
	box-shadow: 0 8rpx 24rpx rgba(60, 156, 255, 0.35);
	display: flex;
	align-items: center;
	justify-content: center;

	&:active {
		background: $color-primary-dark;
	}
}

.bottom-space {
	height: 160rpx;
}
</style>
