import QtQuick
import Quickshell
import ZShell.Config
import ZShell.Components
import ZShell.Llm
import qs.Components
import qs.Services

Item {
	id: root

	required property ChatGeneration current
	required property TextEdit edit
	required property bool hovered
	required property bool isUser
	required property ChatMessage message
	required property LlmSegment segment

	implicitHeight: editButton.implicitHeight
	implicitWidth: generationTools.implicitWidth + editTools.implicitWidth + Tokens.spacing.small

	ButtonRow {
		id: generationTools

		enabled: visible
		visible: !root.isUser

		IconButton {
			enabled: root.message.generationCount > 1 && root.message.activeGenerationIndex !== 0
			icon: "chevron_left"
			type: IconButton.Tonal

			onClicked: {
				if (!root.edit.readOnly)
					root.edit.readOnly = true;
				root.message.setActiveGeneration(root.message.activeGenerationIndex - 1);
			}
		}

		IconButton {
			enabled: false
			icon: `${root.message.activeGenerationIndex + 1}`
			label.font.family: Config.appearance.font.family.sans
			label.font.pointSize: Tokens.font.size.small
			type: IconButton.Text
		}

		IconButton {
			enabled: root.message.generationCount > 1 && root.message.activeGenerationIndex !== root.message.generationCount - 1
			icon: "chevron_right"
			type: IconButton.Tonal

			onClicked: {
				if (!root.edit.readOnly)
					root.edit.readOnly = true;
				root.message.setActiveGeneration(root.message.activeGenerationIndex + 1);
			}
		}
	}

	ButtonRow {
		id: editTools

		anchors.right: parent.right
		opacity: !root.current.streaming && root.hovered ? 1 : 0
		spacing: Tokens.spacing.small
		visible: opacity > 0

		Behavior on opacity {
			Anim {}
		}

		IconButton {
			icon: "refresh"
			inactiveColor: Colors.palette.m3secondary
			inactiveOnColor: Colors.palette.m3onSecondary
			scale: root.edit.readOnly ? 1 : 0
			visible: !root.isUser

			Behavior on scale {
				Anim {}
			}

			onClicked: {
				root.message.retry();
			}
		}

		IconButton {
			icon: "content_copy"
			inactiveColor: Colors.palette.m3secondary
			inactiveOnColor: Colors.palette.m3onSecondary
			scale: root.edit.readOnly ? 1 : 0

			Behavior on scale {
				Anim {}
			}

			onClicked: Quickshell.clipboardText = root.current.content
		}

		IconButton {
			id: editButton

			icon: root.edit.readOnly ? "edit" : "check"
			inactiveColor: Colors.palette.m3tertiary
			inactiveOnColor: Colors.palette.m3onTertiary
			visible: root.isUser

			onClicked: {
				root.edit.readOnly = !root.edit.readOnly;
			}
		}
	}
}
