import type { Ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { describeContinueFeedback } from '../store/subagent_projection';
import type { ChatAttachment, SessionTreeEntry } from '../types/index.d';

type ChatActionsRefs = {
	composerTargetSummary: Ref<{ deliveryTargetTitle: string }>;
	entryById: Ref<Record<string, SessionTreeEntry>>;
	inputContent: Ref<string>;
	selectedEntry: Ref<SessionTreeEntry | null>;
	selectionStateSummary: Ref<{ kind: string }>;
};

type ChatActionsOperations = {
	continueFromEntry: (entryId: string) => Promise<Record<string, unknown>>;
	deleteSession: (sessionId: string) => Promise<unknown>;
	entryTitle: (entry: SessionTreeEntry) => string;
	newSession: () => void;
	pendingSendGuardMessage: (targetTitle: string) => { title: string; message: string };
	selectAgent: (agentId: number | null) => Promise<unknown>;
	selectTreeEntry: (entryId: string) => void;
	sendMessage: (content: string, attachments?: ChatAttachment[]) => Promise<unknown>;
	switchSession: (sessionId: string) => Promise<unknown>;
};

export function useChatActions(refs: ChatActionsRefs, operations: ChatActionsOperations) {
	async function handleAgentChange(value: number | '' | undefined) {
		await operations.selectAgent(value ? Number(value) : null);
	}

	async function handleSessionChange(value: string | '' | undefined) {
		if (!value) {
			handleNewSession();
			return;
		}
		await operations.switchSession(String(value));
	}

	function handleSelectEntry(entryId: string) {
		operations.selectTreeEntry(entryId);
	}

	async function handleContinue(entryId: string) {
		const result = await operations.continueFromEntry(entryId);
		const targetEntry = refs.entryById.value[entryId] || null;
		const feedback = describeContinueFeedback({
			...result,
			title: targetEntry ? operations.entryTitle(targetEntry) : undefined,
		});

		if (feedback.type === 'success') {
			ElMessage.success(feedback.message);
			return;
		}
		if (feedback.type === 'warning') {
			ElMessage.warning(feedback.message);
			return;
		}
		ElMessage.error(feedback.message);
	}

	function handleNewSession() {
		operations.newSession();
		refs.inputContent.value = '';
	}

	async function handleDeleteSession(nextSessionId: string) {
		await operations.deleteSession(nextSessionId);
	}

	async function handleSend(attachments?: ChatAttachment[]) {
		const content = refs.inputContent.value.trim();
		if (!content && !attachments?.length) return;
		if (refs.selectionStateSummary.value.kind === 'pending') {
			const targetTitle = refs.selectedEntry.value
				? operations.entryTitle(refs.selectedEntry.value)
				: refs.composerTargetSummary.value.deliveryTargetTitle;
			const guard = operations.pendingSendGuardMessage(targetTitle);
			try {
				await ElMessageBox.confirm(guard.message, guard.title, {
					confirmButtonText: '仍然发送',
					cancelButtonText: '先不发送',
					type: 'warning',
				});
			} catch {
				return;
			}
		}
		refs.inputContent.value = '';
		await operations.sendMessage(content, attachments);
	}

	function onKeyDown(event: KeyboardEvent) {
		if (event.key !== 'Enter') return;
		if (event.shiftKey || event.ctrlKey || event.metaKey) return;
		event.preventDefault();
		void handleSend();
	}

	return {
		handleAgentChange,
		handleContinue,
		handleDeleteSession,
		handleNewSession,
		handleSelectEntry,
		handleSend,
		handleSessionChange,
		onKeyDown,
	};
}
