import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import type { ServiceTestResult } from "../types";

interface Props {
	/** Current test result (null = not tested yet). Parent clears this when the form input changes. */
	result: ServiceTestResult | null;
	/** Whether the test mutation is in-flight. */
	isPending: boolean;
	/** Whether the "Save anyway" checkbox is checked. */
	saveAnyway: boolean;
	/** Fired when the user clicks "Test credentials". */
	onTest: () => void;
	/** Fired when the "Save anyway" checkbox toggles. */
	onSaveAnywayChange: (checked: boolean) => void;
	/** Disable the Test button (e.g. no draft yet). */
	disabled?: boolean;
}

/**
 * Shared "Test credentials" panel used by both the add-service dialog and the
 * edit-service panel. Purely presentational — the parent owns the test result
 * + saveAnyway state and the mutation hook. This avoids setState-in-effect
 * issues with clearing the result on input change (the parent uses the
 * React-recommended "store previous prop" pattern instead).
 */
export function ServiceTestPanel({
	result,
	isPending,
	saveAnyway,
	onTest,
	onSaveAnywayChange,
	disabled,
}: Props) {
	const testPassed = result?.ok === true;

	return (
		<div className="flex flex-col gap-2">
			<Button
				variant="outline"
				size="sm"
				onClick={onTest}
				disabled={isPending || disabled}
				className="mobile-touch-target"
			>
				{isPending ? "Testing…" : "Test credentials"}
			</Button>
			{result ? (
				<Alert variant={result.ok ? "default" : "destructive"}>
					<AlertDescription>
						{result.ok
							? `✓ Connected${result.evidence ? ` — ${result.evidence}` : ""}`
							: `✗ ${result.detail}`}
					</AlertDescription>
				</Alert>
			) : null}
			<label className="flex items-center gap-2 text-xs text-muted-foreground">
				<input
					type="checkbox"
					checked={saveAnyway}
					onChange={(e) => onSaveAnywayChange(e.target.checked)}
				/>
				Save anyway (skip test)
			</label>
			{!testPassed && !saveAnyway ? (
				<p className="text-xs text-muted-foreground">
					Test credentials or check "Save anyway" to enable the save button.
				</p>
			) : null}
		</div>
	);
}
