<script lang="ts">
  import { Building2, CheckCircle2, CircleDashed, Eye, EyeOff, KeyRound, Plus, Server, Trash2 } from "@lucide/svelte";
  import { siGitea, siGithub, siGitlab, type SimpleIcon } from "simple-icons";
  import { gitIntegrationProviders, organizationNameFromUrl, providerLabel } from "../integrations";
  import type { AppLanguage, AzureDevOpsOrganization, GitIntegrationConfig, GitIntegrationProvider, GitIntegrationSecretUpdate, GitIntegrationSettings } from "../types";

  interface Props {
    language: AppLanguage;
    settings: GitIntegrationSettings;
    onChange: (settings: GitIntegrationSettings) => void;
    onSecretsChange: (updates: GitIntegrationSecretUpdate[]) => void;
  }

  let { language, settings, onChange, onSecretsChange }: Props = $props();
  let selected = $state<GitIntegrationProvider>("github");
  let selectedAzureOrganizationId = $state("");
  let tokenValues = $state<Record<string, string>>({});
  let secretUpdates = $state<Record<string, GitIntegrationSecretUpdate>>({});
  let showToken = $state(false);

  const isGerman = $derived(language === "de");
  const selectedAzureOrganization = $derived(settings.azureDevOpsOrganizations.find((organization) => organization.id === selectedAzureOrganizationId));
  const current = $derived<GitIntegrationConfig | AzureDevOpsOrganization | undefined>(selected === "azure-devops" ? selectedAzureOrganization : settings.providers[selected]);
  const currentAccountId = $derived(selected === "azure-devops" ? selectedAzureOrganization?.id : undefined);

  const azureDevOpsIcon: SimpleIcon = {
    title: "Azure DevOps", slug: "azuredevops", hex: "0078D4", source: "https://azure.microsoft.com/products/devops", svg: "",
    path: "M0 8.877 2.247 5.91l8.405-3.416v19.127l-8.405-3.53L0 15.123V8.877Zm12.154-6.968 11.846 2.423v15.336l-11.846 2.423V1.909Z",
  };
  const providerIcons: Record<GitIntegrationProvider, SimpleIcon> = { github: siGithub, gitlab: siGitlab, "gitlab-self-hosted": siGitlab, "azure-devops": azureDevOpsIcon, gitea: siGitea };

  function providerDescription(provider: GitIntegrationProvider): string {
    const descriptions = isGerman
      ? { github: "Konto auf github.com", gitlab: "Cloud-Konto auf gitlab.com", "gitlab-self-hosted": "Eigene GitLab-Instanz", "azure-devops": "Mehrere Organisationen", gitea: "Cloud- oder eigene Instanz" }
      : { github: "Cloud account on github.com", gitlab: "Cloud account on gitlab.com", "gitlab-self-hosted": "Your own GitLab instance", "azure-devops": "Multiple organizations", gitea: "Cloud or self-hosted instance" };
    return descriptions[provider];
  }

  function providerColor(provider: GitIntegrationProvider): string {
    return provider === "github" ? "var(--color-ink)" : `#${providerIcons[provider].hex}`;
  }

  function secretId(provider: GitIntegrationProvider, accountId?: string): string {
    return accountId ? `${provider}:${accountId}` : provider;
  }

  function emitSecrets() {
    onSecretsChange(Object.values(secretUpdates));
  }

  function updateCurrent(patch: Partial<GitIntegrationConfig & AzureDevOpsOrganization>) {
    if (!current) return;
    if (selected === "azure-devops" && selectedAzureOrganization) {
      onChange({
        ...settings,
        azureDevOpsOrganizations: settings.azureDevOpsOrganizations.map((organization) => organization.id === selectedAzureOrganization.id ? { ...organization, ...patch } : organization),
      });
      return;
    }
    onChange({ ...settings, providers: { ...settings.providers, [selected]: { ...settings.providers[selected], ...patch } } });
  }

  function setToken(value: string) {
    if (!current) return;
    const id = secretId(selected, currentAccountId);
    tokenValues[id] = value;
    if (value.trim()) secretUpdates[id] = { provider: selected, accountId: currentAccountId, token: value };
    else delete secretUpdates[id];
    tokenValues = { ...tokenValues };
    secretUpdates = { ...secretUpdates };
    emitSecrets();
  }

  function forgetToken() {
    if (!current) return;
    const id = secretId(selected, currentAccountId);
    tokenValues[id] = "";
    secretUpdates[id] = { provider: selected, accountId: currentAccountId, removeToken: true };
    tokenValues = { ...tokenValues };
    secretUpdates = { ...secretUpdates };
    updateCurrent({ enabled: false, tokenStored: false });
    emitSecrets();
  }

  function pendingRemoval(provider: GitIntegrationProvider, accountId?: string): boolean {
    return secretUpdates[secretId(provider, accountId)]?.removeToken === true;
  }

  function tokenValue(): string {
    return tokenValues[secretId(selected, currentAccountId)] ?? "";
  }

  function selectProvider(provider: GitIntegrationProvider) {
    selected = provider;
    showToken = false;
    if (provider === "azure-devops" && !settings.azureDevOpsOrganizations.some((organization) => organization.id === selectedAzureOrganizationId)) {
      selectedAzureOrganizationId = settings.azureDevOpsOrganizations[0]?.id ?? "";
    }
  }

  function createOrganizationId(): string {
    if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
    return `org-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  }

  function addAzureOrganization() {
    const id = createOrganizationId();
    const number = settings.azureDevOpsOrganizations.length + 1;
    const organization: AzureDevOpsOrganization = {
      id,
      name: isGerman ? `Organisation ${number}` : `Organization ${number}`,
      enabled: true,
      baseUrl: "https://dev.azure.com/",
      username: "",
      tokenStored: false,
    };
    onChange({ ...settings, azureDevOpsOrganizations: [...settings.azureDevOpsOrganizations, organization] });
    selectedAzureOrganizationId = id;
    showToken = false;
  }

  function removeAzureOrganization(organization: AzureDevOpsOrganization) {
    const id = secretId("azure-devops", organization.id);
    if (organization.tokenStored) secretUpdates[id] = { provider: "azure-devops", accountId: organization.id, removeToken: true };
    else delete secretUpdates[id];
    delete tokenValues[id];
    secretUpdates = { ...secretUpdates };
    tokenValues = { ...tokenValues };
    const remaining = settings.azureDevOpsOrganizations.filter((candidate) => candidate.id !== organization.id);
    onChange({ ...settings, azureDevOpsOrganizations: remaining });
    selectedAzureOrganizationId = remaining[0]?.id ?? "";
    showToken = false;
    emitSecrets();
  }

  function organizationDisplayName(organization: AzureDevOpsOrganization): string {
    return organization.name.trim() || organizationNameFromUrl(organization.baseUrl) || (isGerman ? "Unbenannte Organisation" : "Unnamed organization");
  }

  function isOrganizationConfigured(organization: AzureDevOpsOrganization): boolean {
    return organization.tokenStored && organization.baseUrl.trim().length > 0 && !pendingRemoval("azure-devops", organization.id);
  }

  function isConfigured(provider: GitIntegrationProvider): boolean {
    if (provider === "azure-devops") return settings.azureDevOpsOrganizations.some(isOrganizationConfigured);
    const config = settings.providers[provider];
    return config.tokenStored && config.baseUrl.trim().length > 0 && !pendingRemoval(provider);
  }

  function currentConfigured(): boolean {
    if (!current) return false;
    return current.tokenStored && current.baseUrl.trim().length > 0 && !pendingRemoval(selected, currentAccountId);
  }

  function baseUrlPlaceholder(): string {
    if (selected === "azure-devops") return "https://dev.azure.com/meine-organisation";
    if (selected === "github") return "https://github.com";
    if (selected === "gitlab") return "https://gitlab.com";
    if (selected === "gitlab-self-hosted") return "https://gitlab.example.com";
    return "https://gitea.example.com";
  }
</script>

<div class="integration-layout">
  <div class="integration-providers" role="tablist" aria-label={isGerman ? "Git-Anbieter" : "Git providers"}>
    {#each gitIntegrationProviders as provider}
      <button type="button" role="tab" aria-selected={selected === provider} class:active={selected === provider} onclick={() => selectProvider(provider)}>
        <span class="provider-logo" style={`--provider-color:${providerColor(provider)}`}><svg viewBox="0 0 24 24" aria-hidden="true"><path d={providerIcons[provider].path} /></svg></span>
        <span class="provider-copy"><strong>{providerLabel(provider)}</strong><small>{providerDescription(provider)}</small></span>
        <span class="provider-state" class:configured={isConfigured(provider)} title={isConfigured(provider) ? (isGerman ? "Konfiguriert" : "Configured") : (isGerman ? "Nicht verbunden" : "Not connected")}></span>
      </button>
    {/each}
  </div>

  <section class="integration-config" aria-label={`${providerLabel(selected)} ${isGerman ? "konfigurieren" : "configuration"}`}>
    <header class="integration-summary">
      <span class="provider-logo provider-logo-large" style={`--provider-color:${providerColor(selected)}`}><svg viewBox="0 0 24 24" aria-hidden="true"><path d={providerIcons[selected].path} /></svg></span>
      <div><h4>{providerLabel(selected)}</h4><p>{providerDescription(selected)}</p></div>
      {#if selected === "azure-devops"}
        <span class="integration-status" class:configured={isConfigured(selected)}><Building2 size={13} />{settings.azureDevOpsOrganizations.length} {isGerman ? "Orgas" : "orgs"}</span>
      {:else}
        <span class="integration-status" class:configured={currentConfigured()}>{#if currentConfigured()}<CheckCircle2 size={13} />{:else}<CircleDashed size={13} />{/if}{currentConfigured() ? (isGerman ? "Konfiguriert" : "Configured") : (isGerman ? "Nicht verbunden" : "Not connected")}</span>
      {/if}
    </header>

    {#if selected === "azure-devops"}
      <div class="azure-organizations">
        <div class="azure-organizations-head"><div><strong>{isGerman ? "Organisationen" : "Organizations"}</strong><small>{isGerman ? "Jede Organisation verwendet einen eigenen Token." : "Each organization uses its own token."}</small></div><button type="button" onclick={addAzureOrganization}><Plus size={14} />{isGerman ? "Hinzufügen" : "Add"}</button></div>
        {#if settings.azureDevOpsOrganizations.length === 0}
          <div class="azure-organizations-empty"><Building2 size={22} /><span>{isGerman ? "Noch keine Azure-DevOps-Organisation angelegt." : "No Azure DevOps organization has been added yet."}</span><button type="button" onclick={addAzureOrganization}><Plus size={14} />{isGerman ? "Erste Organisation anlegen" : "Add first organization"}</button></div>
        {:else}
          <div class="azure-organization-list" role="tablist" aria-label={isGerman ? "Azure-DevOps-Organisationen" : "Azure DevOps organizations"}>
            {#each settings.azureDevOpsOrganizations as organization (organization.id)}
              <div class="azure-organization-row" class:active={selectedAzureOrganizationId === organization.id}>
                <button type="button" role="tab" aria-selected={selectedAzureOrganizationId === organization.id} onclick={() => { selectedAzureOrganizationId = organization.id; showToken = false; }}>
                  <span><strong>{organizationDisplayName(organization)}</strong><small>{organization.baseUrl}</small></span><i class:configured={isOrganizationConfigured(organization)}></i>
                </button>
                <button class="azure-remove" type="button" onclick={() => removeAzureOrganization(organization)} title={isGerman ? "Organisation entfernen" : "Remove organization"} aria-label={`${organizationDisplayName(organization)} ${isGerman ? "entfernen" : "remove"}`}><Trash2 size={13} /></button>
              </div>
            {/each}
          </div>
        {/if}
      </div>
    {/if}

    {#if current}
      {#if selected === "azure-devops"}
        <label class="integration-field"><span><Building2 size={13} />{isGerman ? "Anzeigename" : "Display name"}</span><input value={selectedAzureOrganization?.name ?? ""} oninput={(event) => updateCurrent({ name: event.currentTarget.value })} placeholder={isGerman ? "z. B. Contoso Platform" : "e.g. Contoso Platform"} /></label>
      {/if}

      <label class="integration-field">
        <span><Server size={13} />{selected === "azure-devops" ? (isGerman ? "Organisations-URL" : "Organization URL") : (isGerman ? "Server-URL" : "Server URL")}</span>
        <input value={current.baseUrl} oninput={(event) => updateCurrent({ baseUrl: event.currentTarget.value })} placeholder={baseUrlPlaceholder()} spellcheck="false" inputmode="url" />
        <small>{isGerman ? "Basis-URL ohne Repository-Pfad." : "Base URL without a repository path."}</small>
      </label>

      <label class="integration-field"><span>{isGerman ? "Benutzername oder E-Mail" : "Username or email"}</span><input value={current.username} oninput={(event) => updateCurrent({ username: event.currentTarget.value })} autocomplete="off" placeholder={selected === "azure-devops" ? "name@example.com" : (isGerman ? "Benutzername" : "Username")} spellcheck="false" /></label>

      <label class="integration-field">
        <span><KeyRound size={13} />Personal Access Token</span>
        <div class="token-row"><input type={showToken ? "text" : "password"} value={tokenValue()} oninput={(event) => setToken(event.currentTarget.value)} autocomplete="new-password" placeholder={current.tokenStored && !pendingRemoval(selected, currentAccountId) ? (isGerman ? "Token ist sicher gespeichert" : "Token is stored securely") : (isGerman ? "Token einfügen" : "Paste token")} spellcheck="false" /><button type="button" onclick={() => { showToken = !showToken; }} title={showToken ? (isGerman ? "Token ausblenden" : "Hide token") : (isGerman ? "Token anzeigen" : "Show token")} aria-label={showToken ? (isGerman ? "Token ausblenden" : "Hide token") : (isGerman ? "Token anzeigen" : "Show token")}>{#if showToken}<EyeOff size={15} />{:else}<Eye size={15} />{/if}</button></div>
        <small>{isGerman ? "Der Token wird separat im Schlüsselbund des Betriebssystems gespeichert." : "The token is stored separately in the operating system keychain."}</small>
      </label>

      <div class="integration-actions">
        <label class="integration-enabled"><span><strong>{selected === "azure-devops" ? (isGerman ? "Organisation aktivieren" : "Enable organization") : (isGerman ? "Integration aktivieren" : "Enable integration")}</strong><small>{isGerman ? "Für Hosting- und Clone-Funktionen verwenden." : "Use for hosting and clone features."}</small></span><input type="checkbox" checked={current.enabled} onchange={(event) => updateCurrent({ enabled: event.currentTarget.checked })} /></label>
        {#if current.tokenStored && !pendingRemoval(selected, currentAccountId)}<button class="forget-token" type="button" onclick={forgetToken}><Trash2 size={14} />{isGerman ? "Gespeicherten Token entfernen" : "Remove stored token"}</button>{/if}
      </div>
    {/if}
  </section>
</div>

<style>
  .integration-layout { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 14px; min-height: 420px; }
  .integration-providers { display: flex; flex-direction: column; gap: 5px; }
  .integration-providers > button { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; min-height: 64px; padding: 9px 10px; border: 1px solid var(--color-border-subtle); border-radius: 9px; color: var(--color-ink-dim); background: var(--app-settings-row-bg); text-align: left; }
  .integration-providers > button:hover { color: var(--color-ink); border-color: var(--color-border); background: var(--color-surface-hover); }
  .integration-providers > button.active { border-color: color-mix(in srgb, var(--color-accent) 34%, var(--color-border)); color: var(--color-ink); background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface-raised)); box-shadow: inset 2px 0 0 var(--color-accent); }
  .provider-logo { display: grid; place-items: center; width: 32px; height: 32px; border: 1px solid color-mix(in srgb, var(--provider-color) 34%, var(--color-border)); border-radius: 8px; color: var(--provider-color); background: color-mix(in srgb, var(--provider-color) 10%, transparent); }
  .provider-logo svg { width: 17px; height: 17px; fill: currentColor; }
  .provider-logo-large { width: 42px; height: 42px; border-radius: 10px; }
  .provider-logo-large svg { width: 22px; height: 22px; }
  .provider-copy { display: grid; min-width: 0; gap: 3px; }
  .provider-copy strong { color: inherit; font-size: 11px; }
  .provider-copy small { overflow: hidden; color: var(--color-ink-faint); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
  .provider-state { width: 7px; height: 7px; border-radius: 50%; background: var(--color-ink-faint); }
  .provider-state.configured { background: var(--color-success); box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-success) 12%, transparent); }
  .integration-config { display: grid; align-content: start; gap: 13px; min-width: 0; padding: 16px; border: 1px solid var(--color-border-subtle); border-radius: 12px; background: color-mix(in srgb, var(--app-settings-row-bg) 72%, transparent); }
  .integration-summary { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding-bottom: 13px; border-bottom: 1px solid var(--color-border-subtle); }
  .integration-summary h4 { margin: 0; color: var(--color-ink); font-size: 14px; }
  .integration-summary p { margin: 3px 0 0; color: var(--color-ink-dim); font-size: 10.5px; }
  .integration-status { display: inline-flex; align-items: center; gap: 5px; padding: 5px 7px; border: 1px solid var(--color-border-subtle); border-radius: 6px; color: var(--color-ink-faint); font-size: 9px; font-weight: 750; }
  .integration-status.configured { border-color: color-mix(in srgb, var(--color-success) 24%, var(--color-border)); color: var(--color-success); background: color-mix(in srgb, var(--color-success) 6%, transparent); }
  .azure-organizations { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--color-border-subtle); border-radius: 9px; background: var(--color-surface-raised); }
  .azure-organizations-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
  .azure-organizations-head > div { display: grid; gap: 2px; }
  .azure-organizations-head strong { color: var(--color-ink); font-size: 10.5px; }
  .azure-organizations-head small { color: var(--color-ink-faint); font-size: 8.5px; }
  .azure-organizations-head button, .azure-organizations-empty button { min-height: 27px; padding: 0 8px; font-size: 9.5px; font-weight: 750; }
  .azure-organization-list { display: grid; gap: 5px; max-height: 142px; overflow: auto; }
  .azure-organization-row { display: grid; grid-template-columns: minmax(0, 1fr) 30px; gap: 4px; border: 1px solid var(--color-border-subtle); border-radius: 7px; background: color-mix(in srgb, var(--app-settings-row-bg) 72%, transparent); }
  .azure-organization-row.active { border-color: color-mix(in srgb, var(--color-accent) 38%, var(--color-border)); box-shadow: inset 2px 0 0 var(--color-accent); }
  .azure-organization-row > button:first-child { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; min-height: 42px; padding: 5px 8px; border: 0; color: var(--color-ink-dim); background: transparent; text-align: left; }
  .azure-organization-row > button:first-child span { display: grid; min-width: 0; gap: 2px; }
  .azure-organization-row strong, .azure-organization-row small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .azure-organization-row strong { color: var(--color-ink); font-size: 10px; }
  .azure-organization-row small { color: var(--color-ink-faint); font-size: 8.5px; }
  .azure-organization-row i { width: 6px; height: 6px; border-radius: 50%; background: var(--color-ink-faint); }
  .azure-organization-row i.configured { background: var(--color-success); }
  .azure-remove { min-height: 30px; align-self: center; padding: 0; border: 0; color: var(--color-ink-faint); background: transparent; }
  .azure-remove:hover { color: #e86060; background: color-mix(in srgb, #e86060 8%, transparent); }
  .azure-organizations-empty { display: grid; place-items: center; gap: 7px; padding: 14px; color: var(--color-ink-faint); text-align: center; }
  .azure-organizations-empty > :global(svg) { color: var(--color-accent); }
  .azure-organizations-empty span { font-size: 9.5px; }
  .integration-field { display: grid; gap: 6px; min-width: 0; color: var(--color-ink-muted); font-size: 10.5px; font-weight: 750; }
  .integration-field > span { display: flex; align-items: center; gap: 5px; }
  .integration-field input { height: 36px; border-color: var(--color-border); background: var(--color-surface-raised); font-size: 11px; }
  .integration-field small { color: var(--color-ink-faint); font-size: 9.5px; font-weight: 500; }
  .token-row { display: grid; grid-template-columns: minmax(0, 1fr) 36px; gap: 6px; }
  .token-row button { display: grid; place-items: center; min-height: 36px; padding: 0; }
  .integration-actions { display: grid; gap: 10px; padding-top: 2px; }
  .integration-enabled { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; padding: 11px 12px; border: 1px solid var(--color-border-subtle); border-radius: 8px; background: var(--color-surface-raised); }
  .integration-enabled > span { display: grid; gap: 3px; }
  .integration-enabled strong { color: var(--color-ink); font-size: 10.5px; }
  .integration-enabled small { color: var(--color-ink-faint); font-size: 9px; }
  .integration-enabled input { width: 32px; height: 18px; accent-color: var(--color-accent); }
  .forget-token { justify-self: start; min-height: 28px; color: #e86060; font-size: 10px; }
  @media (max-width: 680px) { .integration-layout { grid-template-columns: 1fr; min-height: 0; } .integration-providers { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } .integration-providers > button { min-height: 54px; } .provider-copy small { display: none; } }
  @media (max-width: 430px) { .integration-providers { grid-template-columns: 1fr; } .integration-summary { grid-template-columns: auto minmax(0, 1fr); } .integration-status { grid-column: 1 / -1; justify-self: start; } .azure-organizations-head { align-items: stretch; flex-direction: column; } .azure-organizations-head button { align-self: start; } }
</style>
