import { Link } from "react-router-dom";
import { useChatContext } from "../../context/ChatContext";
import { SessionList } from "../session/SessionList";
import styles from "./Sidebar.module.css";

export function Sidebar() {
	const { connected, isStreaming, sidebarOpen, loadSessions, newSession } = useChatContext();

	const statusDotClass = connected
		? isStreaming
			? `${styles.statusDot} ${styles.streaming}`
			: `${styles.statusDot} ${styles.connected}`
		: `${styles.statusDot} ${styles.disconnected}`;

	const statusText = !connected ? "未连接" : isStreaming ? "输入中..." : "就绪";

	return (
		<aside className={`${styles.sidebar} ${sidebarOpen ? styles.open : ""}`}>
			<div className={styles.header}>
				<div className={styles.brand}>
					<img className={styles.logo} src="/logo.png" width={36} height={36} alt="" decoding="async" />
					<h2 className={styles.title}>萌小芽</h2>
				</div>
			</div>

			<div className={styles.section}>
				<div className={styles.sectionHeader}>
					<span>历史会话</span>
					<button type="button" className={styles.sectionRefresh} onClick={() => void loadSessions()} title="刷新">
						<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
							<path d="M1 4v6h6M23 20v-6h-6" />
							<path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15" />
						</svg>
					</button>
				</div>
				<SessionList />
			</div>

			<div className={styles.actions}>
				<button type="button" className={styles.actionBtn} onClick={newSession}>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
						<path d="M12 5v14M5 12h14" />
					</svg>
					新会话
				</button>
				<Link to="/settings" className={styles.actionBtn}>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
						<circle cx="12" cy="12" r="3" />
						<path d="M19.4 15a1.7 1.7 0 00.3 1.9l.1.1a2 2 0 01-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.9-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 01-4 0v-.1a1.7 1.7 0 00-1-1.5 1.7 1.7 0 00-1.9.3l-.1.1A2 2 0 014.2 17l.1-.1A1.7 1.7 0 004.6 15a1.7 1.7 0 00-1.5-1H3a2 2 0 010-4h.1a1.7 1.7 0 001.5-1 1.7 1.7 0 00-.3-1.9L4.2 7A2 2 0 017 4.2l.1.1A1.7 1.7 0 009 4.6a1.7 1.7 0 001-1.5V3a2 2 0 014 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.9-.3l.1-.1A2 2 0 0119.8 7l-.1.1a1.7 1.7 0 00-.3 1.9 1.7 1.7 0 001.5 1h.1a2 2 0 010 4h-.1a1.7 1.7 0 00-1.5 1z" />
					</svg>
					设置
				</Link>
			</div>

			<div className={styles.status}>
				<div className={styles.statusRow}>
					<span className={statusDotClass} />
					<span>{statusText}</span>
				</div>
			</div>
		</aside>
	);
}
