import { useState } from "react";
import { useChatContext } from "../../context/ChatContext";
import { formatTimeAgo } from "../../utils/format";
import { formatSessionTitle } from "../../utils/sessionTitle";
import styles from "./SessionList.module.css";

export function SessionList() {
	const {
		sessions,
		activeSessionPath,
		isEphemeralSession,
		loadSession,
		newTemporarySession,
		deleteSession,
		renameSession,
		toggleSessionPin,
	} = useChatContext();
	const [editingPath, setEditingPath] = useState<string | null>(null);
	const [editingValue, setEditingValue] = useState("");

	const startEditing = (path: string, currentName: string) => {
		setEditingPath(path);
		setEditingValue(currentName);
	};

	const confirmRename = (path: string) => {
		const trimmed = editingValue.trim();
		if (trimmed) {
			void renameSession(path, trimmed);
		}
		setEditingPath(null);
		setEditingValue("");
	};

	const cancelEditing = () => {
		setEditingPath(null);
		setEditingValue("");
	};

	return (
		<div className={styles.list}>
			<div className={`${styles.item} ${isEphemeralSession ? styles.active : ""} ${styles.ephemeral}`}>
				<button type="button" className={styles.main} onClick={newTemporarySession}>
					<div className={styles.name}>临时对话</div>
					<div className={styles.meta}>不保存 · 刷新后消失</div>
				</button>
			</div>

			{sessions.length === 0 ? (
				<div className={styles.emptyInline}>暂无历史会话</div>
			) : (
				sessions.map((s) => {
					const isActive = !isEphemeralSession && activeSessionPath === s.path;
					const isPinned = Boolean(s.pinned);
					const title = formatSessionTitle(s.name);
					const isEditing = editingPath === s.path;
					return (
						<div
							key={s.path}
							className={`${styles.item} ${isActive ? styles.active : ""} ${isPinned ? styles.pinned : ""}`}
						>
							<button type="button" className={styles.main} onClick={() => void loadSession(s.path)}>
								<div className={styles.titleRow}>
									{isEditing ? (
										<input
											className={styles.renameInput}
											value={editingValue}
											onChange={(e) => setEditingValue(e.target.value)}
											onKeyDown={(e) => {
												if (e.key === "Enter") {
													e.preventDefault();
													confirmRename(s.path);
												} else if (e.key === "Escape") {
													cancelEditing();
												}
											}}
											onBlur={() => confirmRename(s.path)}
											onClick={(e) => e.stopPropagation()}
											autoFocus
										/>
									) : (
										<div className={styles.name}>{title}</div>
									)}
								</div>
								<div className={styles.meta}>
									{s.messageCount ?? 0} 条 · {formatTimeAgo(s.modified || s.created)}
								</div>
							</button>
							<div className={styles.actions}>
								<button
									type="button"
									className={`${styles.pinBtn} ${isPinned ? styles.pinBtnActive : ""}`}
									title={isPinned ? "取消置顶" : "置顶会话"}
									aria-label={isPinned ? `取消置顶 ${title}` : `置顶 ${title}`}
									onClick={(e) => {
										e.stopPropagation();
										void toggleSessionPin(s.path, !isPinned);
									}}
								>
									<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
										<path d="M12 17v5" />
										<path d="M9 3h6l1 7h4l-5 6v4H9v-4L4 10h4l1-7z" />
									</svg>
								</button>
								<button
									type="button"
									className={styles.renameBtn}
									title="重命名会话"
									aria-label={`重命名 ${title}`}
									onClick={(e) => {
										e.stopPropagation();
										if (isEditing) {
											cancelEditing();
										} else {
											startEditing(s.path, s.name || title);
										}
									}}
								>
									<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
										<path d="M12 20h9" />
										<path d="M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4 12.5-12.5z" />
									</svg>
								</button>
								<button
									type="button"
									className={styles.deleteBtn}
									title="删除会话"
									aria-label={`删除 ${title}`}
									onClick={(e) => {
										e.stopPropagation();
										void deleteSession(s.path);
									}}
								>
									<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
										<path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" />
									</svg>
								</button>
							</div>
						</div>
					);
				})
			)}
		</div>
	);
}
