<script lang="ts">
	import { sendUserToast } from '$lib/utils'
	import { Button, Alert } from '$lib/components/common'
	import Label from '$lib/components/Label.svelte'
	import { Save, ExternalLink } from 'lucide-svelte'
	import { workspaceStore } from '$lib/stores'

	interface Props {
		serviceName: string
		serviceDisplayName: string
		existingConfig?: {
			client_id: string
			client_secret: string
			base_url: string
		} | null
		redirectUri: string
		onConfigSaved: (oauthData: any) => Promise<void>
	}

	let {
		serviceName,
		serviceDisplayName,
		existingConfig,
		onConfigSaved,
		redirectUri = $bindable('')
	}: Props = $props()

	let saving = $state(false)
	let clientId = $state('')
	let clientSecret = $state('')
	let baseUrl = $state('')
	let workspace = $workspaceStore!
	redirectUri = `${window.location.origin}/workspace_settings?tab=native_triggers&service=${serviceName}&workspace=${workspace}`
	$effect(() => {
		if (existingConfig) {
			clientId = existingConfig.client_id
			clientSecret = existingConfig.client_secret
			baseUrl = existingConfig.base_url
		}
	})

	async function saveConfig() {
		if (!clientId.trim() || !clientSecret.trim() || !baseUrl.trim()) {
			sendUserToast('Please fill in all fields', true)
			return
		}

		saving = true
		try {
			const oauthData = {
				client_id: clientId.trim(),
				client_secret: clientSecret.trim(),
				base_url: baseUrl.trim().replace(/\/+$/, ''),
				redirect_uri: redirectUri.trim()
			}

			await onConfigSaved(oauthData)
			resetForm()
		} catch (err: any) {
			sendUserToast(`Failed to configure OAuth client: ${err.message}`, true)
		} finally {
			saving = false
		}
	}

	function resetForm() {
		clientId = ''
		clientSecret = ''
	}

	function copyToClipboard(text: string, label: string) {
		navigator.clipboard
			.writeText(text)
			.then(() => {
				sendUserToast(`${label} copied to clipboard`)
			})
			.catch(() => {
				sendUserToast(`Failed to copy ${label}`, true)
			})
	}
</script>

<div class="space-y-4">
	<div class="flex justify-between items-center">
		<h4 class="text-md font-medium text-primary">{serviceDisplayName} OAuth Client Configuration</h4
		>
	</div>

	{#if !existingConfig}
		<Alert type="warning" title="OAuth client required">
			<p class="text-sm mb-2">
				Before you can connect to {serviceDisplayName}, you need to configure an OAuth client. This
				requires:
			</p>
			<ol class="list-decimal list-inside space-y-1 text-sm">
				<li
					>Create an OAuth2 application in your {serviceDisplayName} instance (Administration settings
					-> Security -> OAuth 2.0 clients)</li
				>
				<li
					>Configure the redirect URI: <code
						class="text-xs bg-gray-100 dark:bg-gray-800 px-1 rounded"
						>{redirectUri ||
							`${window.location.origin}/workspace_settings?tab=integrations&service=${serviceName}`}</code
					></li
				>
				<li>Enter the client credentials below</li>
			</ol>
		</Alert>
	{/if}

	<div class="space-y-4">
		<div class="space-y-4">
			<div class="flex flex-col gap-1">
				<Label label="Nextcloud base URL" />
				<p class="text-xs font-normal text-secondary"
					>The base URL of your Nextcloud instance (without trailing slash)</p
				>
				<input
					type="url"
					bind:value={baseUrl}
					placeholder="https://your-nextcloud.example.com"
					class="windmill-input"
					disabled={saving}
				/>
				{#if baseUrl}
					<Button
						wrapperClasses="self-start"
						href={`${baseUrl}/settings/admin/security`}
						target="_blank"
						startIcon={{ icon: ExternalLink }}
					>
						{serviceDisplayName} OAuth Settings
					</Button>
				{/if}
			</div>

			<div class="flex flex-col gap-1">
				<Label label="Redirect URI" />
				<p class="text-xs font-normal text-secondary"
					>Use this URL when creating the OAuth app in {serviceDisplayName}</p
				>
				<div class="flex gap-2">
					<input
						type="url"
						bind:value={redirectUri}
						readonly
						class="windmill-input flex-1 bg-gray-50 dark:bg-gray-900"
					/>
					<Button
						size="xs"
						color="light"
						variant="border"
						onclick={() => copyToClipboard(redirectUri, 'Redirect URI')}
					>
						Copy
					</Button>
				</div>
			</div>

			<div class="flex flex-col gap-1">
				<Label label="Client ID" />
				<input
					type="text"
					bind:value={clientId}
					placeholder="Generated by Nextcloud OAuth app"
					class="windmill-input"
					disabled={saving}
				/>
			</div>

			<div class="flex flex-col gap-1">
				<Label label="Client secret" />
				<input
					type="password"
					bind:value={clientSecret}
					placeholder="Generated by Nextcloud OAuth app"
					class="windmill-input"
					disabled={saving}
				/>
			</div>

			<div class="flex gap-2">
				<Button
					color="blue"
					onclick={saveConfig}
					disabled={saving || !clientId.trim() || !clientSecret.trim() || !baseUrl.trim()}
					startIcon={{ icon: Save }}
				>
					{saving ? 'Saving...' : 'Save configuration'}
				</Button>
			</div>
		</div>
	</div>

	{#if existingConfig}
		<Alert type="success" title="OAuth client configured">
			<p class="text-sm">
				OAuth client is configured for {serviceDisplayName}. You can now connect this workspace to
				your {serviceDisplayName} instance.
			</p>
		</Alert>
	{/if}
</div>
