import { useState, useEffect, FormEvent } from "react"
import { VSCodeTextArea, VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react"

import { supportPrompt, SupportPromptType } from "@roo/support-prompt"

import { vscode } from "@src/utils/vscode"
import { useAppTranslation } from "@src/i18n/TranslationContext"
import { useExtensionState } from "@src/context/ExtensionStateContext"
import {
	Button,
	SearchableSelect,
	// Select,
	// SelectContent,
	// SelectItem,
	// SelectTrigger,
	// SelectValue,
	StandardTooltip,
} from "@src/components/ui"

import { SectionHeader } from "./SectionHeader"
import { Section } from "./Section"
import { Trans } from "react-i18next"
import { SearchableSetting } from "./SearchableSetting"

interface PromptsSettingsProps {
	customSupportPrompts: Record<string, string | undefined>
	setCustomSupportPrompts: (prompts: Record<string, string | undefined>) => void
	includeTaskHistoryInEnhance?: boolean
	setIncludeTaskHistoryInEnhance?: (value: boolean) => void
}

const PromptsSettings = ({
	customSupportPrompts,
	setCustomSupportPrompts,
	includeTaskHistoryInEnhance: propsIncludeTaskHistoryInEnhance,
	setIncludeTaskHistoryInEnhance: propsSetIncludeTaskHistoryInEnhance,
}: PromptsSettingsProps) => {
	const { t } = useAppTranslation()
	const {
		// listApiConfigMeta,
		// enhancementApiConfigId,
		// setEnhancementApiConfigId,
		includeTaskHistoryInEnhance: contextIncludeTaskHistoryInEnhance,
		setIncludeTaskHistoryInEnhance: contextSetIncludeTaskHistoryInEnhance,
	} = useExtensionState()

	// Use props if provided, otherwise fall back to context
	const includeTaskHistoryInEnhance = propsIncludeTaskHistoryInEnhance ?? contextIncludeTaskHistoryInEnhance ?? true
	const setIncludeTaskHistoryInEnhance = propsSetIncludeTaskHistoryInEnhance ?? contextSetIncludeTaskHistoryInEnhance

	const [testPrompt, setTestPrompt] = useState("")
	const [isEnhancing, setIsEnhancing] = useState(false)
	const [activeSupportOption, setActiveSupportOption] = useState<SupportPromptType>("ENHANCE")

	useEffect(() => {
		const handler = (event: MessageEvent) => {
			const message = event.data
			if (message.type === "enhancedPrompt") {
				if (message.text) {
					setTestPrompt(message.text)
				}
				setIsEnhancing(false)
			}
		}

		window.addEventListener("message", handler)
		return () => window.removeEventListener("message", handler)
	}, [])

	const updateSupportPrompt = (type: SupportPromptType, value: string | undefined) => {
		// Don't trim during editing to preserve intentional whitespace
		// Use nullish coalescing to preserve empty strings
		const finalValue = value ?? undefined

		const updatedPrompts = { ...customSupportPrompts }
		if (finalValue === undefined) {
			delete updatedPrompts[type]
		} else {
			updatedPrompts[type] = finalValue
		}
		setCustomSupportPrompts(updatedPrompts)
	}

	const handleSupportReset = (type: SupportPromptType) => {
		const updatedPrompts = { ...customSupportPrompts }
		delete updatedPrompts[type]
		setCustomSupportPrompts(updatedPrompts)
	}

	const getSupportPromptValue = (type: SupportPromptType): string => {
		return supportPrompt.get(customSupportPrompts, type)
	}

	const handleTestEnhancement = () => {
		if (!testPrompt?.trim()) return

		setIsEnhancing(true)
		vscode.postMessage({
			type: "enhancePrompt",
			text: testPrompt,
		})
	}

	return (
		<div>
			<SectionHeader
				description={
					<Trans
						i18nKey="settings:prompts.description"
						components={{
							DocsLink: (
								<a
									href="https://docs.costrict.ai/product-features/prompt"
									target="_blank"
									rel="noopener noreferrer"
									className="text-vscode-textLink-foreground hover:underline">
									{t("common:docsLink.label")}
								</a>
							),
						}}></Trans>
				}>
				{t("settings:sections.prompts")}
			</SectionHeader>

			<Section>
				<SearchableSetting
					settingId="prompts-support-prompt-select"
					section="prompts"
					label={t("settings:sections.prompts")}>
					<SearchableSelect
						value={activeSupportOption}
						onValueChange={(type) => setActiveSupportOption(type as SupportPromptType)}
						options={Object.keys(supportPrompt.default)
							.filter((type) => type !== "CONDENSE")
							.map((type) => ({
								value: type,
								label: t(`prompts:supportPrompts.types.${type}.label`),
							}))}
						placeholder={t("settings:common.select")}
						searchPlaceholder={""}
						emptyMessage={""}
						className="w-full"
						data-testid="provider-select"
					/>
					<div className="text-sm text-vscode-descriptionForeground mt-1">
						{t(`prompts:supportPrompts.types.${activeSupportOption}.description`)}
					</div>
				</SearchableSetting>

				<div key={activeSupportOption} className="mt-4">
					<div className="flex justify-between items-center mb-1">
						<label className="block font-medium">{t("prompts:supportPrompts.prompt")}</label>
						<StandardTooltip
							content={t("prompts:supportPrompts.resetPrompt", {
								promptType: activeSupportOption,
							})}>
							<Button variant="ghost" size="icon" onClick={() => handleSupportReset(activeSupportOption)}>
								<span className="codicon codicon-discard"></span>
							</Button>
						</StandardTooltip>
					</div>

					<VSCodeTextArea
						resize="vertical"
						value={getSupportPromptValue(activeSupportOption)}
						onInput={(e) => {
							const value =
								(e as unknown as CustomEvent)?.detail?.target?.value ??
								((e as any).target as HTMLTextAreaElement).value
							updateSupportPrompt(activeSupportOption, value)
						}}
						rows={6}
						className="w-full"
					/>

					{activeSupportOption === "ENHANCE" && (
						<div className="mt-4 flex flex-col gap-3 pl-3 border-l-2 border-vscode-button-background">
							{/* <div>
								<label className="block font-medium mb-1">
									{t("prompts:supportPrompts.enhance.apiConfiguration")}
								</label>
								<Select
									value={enhancementApiConfigId || "-"}
									onValueChange={(value) => {
										const newConfigId = value === "-" ? "" : value
										setEnhancementApiConfigId(newConfigId)
										vscode.postMessage({
											type: "enhancementApiConfigId",
											text: value,
										})
									}}>
									<SelectTrigger data-testid="api-config-select" className="w-full">
										<SelectValue
											placeholder={t("prompts:supportPrompts.enhance.useCurrentConfig")}
										/>
									</SelectTrigger>
									<SelectContent>
										<SelectItem value="-">
											{t("prompts:supportPrompts.enhance.useCurrentConfig")}
										</SelectItem>
										{(listApiConfigMeta || []).map((config) => (
											<SelectItem
												key={config.id}
												value={config.id}
												data-testid={`${config.id}-option`}>
												{config.name}
											</SelectItem>
										))}
									</SelectContent>
								</Select>
								<div className="text-sm text-vscode-descriptionForeground mt-1">
									{t("prompts:supportPrompts.enhance.apiConfigDescription")}
								</div>
							</div> */}

							<div>
								<VSCodeCheckbox
									checked={includeTaskHistoryInEnhance}
									onChange={(e: Event | FormEvent<HTMLElement>) => {
										const target = ("target" in e ? e.target : null) as HTMLInputElement | null

										if (!target) {
											return
										}

										setIncludeTaskHistoryInEnhance(target.checked)

										vscode.postMessage({
											type: "updateSettings",
											updatedSettings: { includeTaskHistoryInEnhance: target.checked },
										})
									}}>
									<span className="font-medium">
										{t("prompts:supportPrompts.enhance.includeTaskHistory")}
									</span>
								</VSCodeCheckbox>
								<div className="text-vscode-descriptionForeground text-sm mt-1 mb-3">
									{t("prompts:supportPrompts.enhance.includeTaskHistoryDescription")}
								</div>
							</div>

							<div>
								<label className="block font-medium mb-1">
									{t("prompts:supportPrompts.enhance.testEnhancement")}
								</label>
								<VSCodeTextArea
									resize="vertical"
									value={testPrompt}
									onChange={(e) => setTestPrompt((e.target as HTMLTextAreaElement).value)}
									placeholder={t("prompts:supportPrompts.enhance.testPromptPlaceholder")}
									rows={3}
									className="w-full"
									data-testid="test-prompt-textarea"
								/>
								<div className="mt-2 flex justify-start items-center gap-2">
									<Button variant="primary" onClick={handleTestEnhancement} disabled={isEnhancing}>
										{t("prompts:supportPrompts.enhance.previewButton")}
									</Button>
								</div>
							</div>
						</div>
					)}
				</div>
			</Section>
		</div>
	)
}

export default PromptsSettings
