<script lang="ts">
  import { Cloud, GitBranch, Plus, Save, Trash2, X } from "@lucide/svelte";
  import type { GitRemote, PullStrategy } from "../types";
  import SelectMenu from "./SelectMenu.svelte";

  export let remotes: GitRemote[] = [];
  export let remoteBranches: string[] = [];
  export let currentBranch = "";
  export let currentUpstream = "";
  export let strategy: PullStrategy = "merge";
  export let selectedRemote = "";
  export let isBusy = false;
  export let language: "en" | "de" = "en";
  export let onSaveSync: (strategy: PullStrategy, remote: string, upstream: string) => void | Promise<void> = () => {};
  export let onAddRemote: (name: string, url: string) => void | Promise<void> = () => {};
  export let onUpdateRemote: (name: string, url: string) => void | Promise<void> = () => {};
  export let onRemoveRemote: (name: string) => void | Promise<void> = () => {};
  export let onClose: () => void = () => {};

  let draftStrategy = strategy;
  let draftRemote = selectedRemote;
  let draftUpstream = currentUpstream;
  let newName = "origin";
  let newUrl = "";
  let editingName = "";
  let editingUrl = "";
  let actionError = "";
  let actionStatus = "";
  $: de = language === "de";

  function beginEdit(remote: GitRemote) { actionError = ""; editingName = remote.name; editingUrl = remote.fetch_url; }
  async function requestDelete(event: MouseEvent, name: string) {
    console.log(name)
    event.preventDefault();
    event.stopPropagation();
    editingName = "";
    actionError = "";
    actionStatus = de ? `Remote „${name}“ wird entfernt …` : `Removing remote “${name}” …`;
    console.info("[Gitty remote] remove button activated", { name });
    await remove(name);
  }
  function cancelEdit() { editingName = ""; editingUrl = ""; }
  async function add() { if (!newName.trim() || !newUrl.trim()) return; await onAddRemote(newName.trim(), newUrl.trim()); newName = "origin"; newUrl = ""; }
  async function update() { if (!editingName || !editingUrl.trim()) return; await onUpdateRemote(editingName, editingUrl.trim()); cancelEdit(); }
  async function remove(name: string) {
    actionError = "";
    console.log("remove")
    try {
      await onRemoveRemote(name);
      if (draftRemote === name) draftRemote = "";
      if (draftUpstream.startsWith(`${name}/`)) draftUpstream = "";
    } catch (error) {
      actionError = error instanceof Error ? error.message : String(error);
    } finally {
      actionStatus = "";
    }
  }
</script>

<div class="dialog-backdrop" role="presentation">
  <div class="sync-settings-dialog" role="dialog" aria-modal="true" aria-labelledby="sync-settings-title">
    <header class="sync-settings-head">
      <div class="sync-settings-title">
        <span class="sync-settings-icon"><Cloud size={18} aria-hidden="true" /></span>
        <div><span class="eyebrow">Git sync</span><h2 id="sync-settings-title">{de ? "Synchronisierung & Remotes" : "Sync & remotes"}</h2></div>
      </div>
      <button class="dialog-icon-button" type="button" onclick={onClose} disabled={isBusy} aria-label={de ? "Schließen" : "Close"}><X size={17} /></button>
    </header>

    <div class="sync-settings-body">
      <section class="sync-settings-card">
        <div class="sync-card-heading"><div><h3>{de ? "Pull-Verhalten" : "Pull behavior"}</h3><p>{de ? "Legt fest, wie entfernte Änderungen in deinen aktuellen Branch übernommen werden." : "Controls how remote changes are integrated into your current branch."}</p></div></div>
        <div class="strategy-options">
          <label class:active={draftStrategy === "merge"}><input type="radio" bind:group={draftStrategy} value="merge" /><span><strong>Merge</strong><small>{de ? "Erstellt bei getrennten Verläufen einen Merge-Commit. Sicher und leicht nachvollziehbar." : "Creates a merge commit for diverged history. Safe and easy to follow."}</small></span></label>
          <label class:active={draftStrategy === "rebase"}><input type="radio" bind:group={draftStrategy} value="rebase" /><span><strong>Rebase</strong><small>{de ? "Setzt deine lokalen Commits auf die Remote-Änderungen. Ergibt eine lineare Historie." : "Replays your local commits on remote changes for a linear history."}</small></span></label>
          <label class:active={draftStrategy === "ff-only"}><input type="radio" bind:group={draftStrategy} value="ff-only" /><span><strong>Fast-forward only</strong><small>{de ? "Pull stoppt, sobald ein Merge nötig wäre. Verändert die Historie nie automatisch." : "Stops when a merge would be required. Never combines diverged history automatically."}</small></span></label>
        </div>

        <div class="sync-fields">
          <label><span>{de ? "Remote für Sync" : "Remote used for sync"}</span><SelectMenu value={draftRemote} options={[{ value: "", label: de ? "Automatisch wählen" : "Choose automatically" }, ...remotes.map((remote) => ({ value: remote.name, label: remote.name }))]} onChange={(value) => { draftRemote = value; }} /><small>{de ? "Ein Remote ist die gespeicherte Verbindung zu einem Server-Repository." : "A remote is a saved connection to a repository on a server."}</small></label>
          <label><span>{de ? `Upstream für ${currentBranch || "aktuellen Branch"}` : `Upstream for ${currentBranch || "current branch"}`}</span><SelectMenu value={draftUpstream} options={[{ value: "", label: de ? "Kein Upstream" : "No upstream" }, ...remoteBranches.map((branch) => ({ value: branch, label: branch }))]} onChange={(value) => { draftUpstream = value; }} /><small>{de ? "Der Upstream ist der Remote-Branch, mit dem Pull, Push und Ahead/Behind verglichen werden." : "The upstream is the remote branch used by Pull, Push, and Ahead/Behind."}</small></label>
        </div>
      </section>

      <section class="sync-settings-card">
        <div class="sync-card-heading"><div><h3>Remotes</h3><p>{de ? "Server-Verbindungen dieses Repositorys verwalten." : "Manage this repository's server connections."}</p></div><span class="count-pill">{remotes.length}</span></div>
        <div class="remote-list">
          {#if actionError}<div class="sync-action-error" role="alert"><strong>{de ? "Remote konnte nicht entfernt werden" : "Remote could not be removed"}</strong><span>{actionError}</span></div>{/if}
          {#if actionStatus}<div class="sync-action-status" role="status">{actionStatus}</div>{/if}
          {#each remotes as remote (remote.name)}
            <div class="remote-row">
              <span class="remote-mark"><GitBranch size={15} /></span>
              {#if editingName === remote.name}
                <div class="remote-edit"><strong>{remote.name}</strong><input bind:value={editingUrl} aria-label={`URL for ${remote.name}`} /></div>
                <button class="btn-sm" type="button" onclick={update} disabled={isBusy || !editingUrl.trim()}><Save size={13} /> {de ? "Speichern" : "Save"}</button>
                <button class="btn-sm" type="button" onclick={cancelEdit} disabled={isBusy}>{de ? "Abbrechen" : "Cancel"}</button>
              {:else}
                <button class="remote-main" type="button" onclick={() => beginEdit(remote)} disabled={isBusy}><strong>{remote.name}</strong><span>{remote.fetch_url}</span></button>
                <button class="remote-delete" type="button" onclick={(event) => requestDelete(event, remote.name)} data-remote-name={remote.name} title={de ? "Remote-Verbindung sofort entfernen; lokale Daten bleiben erhalten" : "Remove remote connection now; local data is kept"}><Trash2 size={13} /><span>{de ? "Entfernen" : "Remove"}</span></button>
              {/if}
            </div>
          {:else}<p class="remote-empty">{de ? "Noch kein Remote eingerichtet." : "No remote configured yet."}</p>{/each}
        </div>
        <div class="remote-add"><input bind:value={newName} placeholder={de ? "Name, z. B. origin" : "Name, e.g. origin"} aria-label="Remote name" /><input bind:value={newUrl} placeholder="https://… or git@…" aria-label="Remote URL" /><button class="btn-secondary" type="button" onclick={add} disabled={isBusy || !newName.trim() || !newUrl.trim()}><Plus size={14} /> {de ? "Hinzufügen" : "Add remote"}</button></div>
      </section>
    </div>

    <footer class="sync-settings-footer"><p>{de ? "Fetch + Prune entfernt veraltete Remote-Verweise. Force with lease ist ein geschütztes Force-Push nach einem Rebase." : "Fetch + Prune removes stale remote references. Force with lease is a protected force-push after a rebase."}</p><div><button class="btn-secondary" type="button" onclick={onClose} disabled={isBusy}>{de ? "Abbrechen" : "Cancel"}</button><button class="btn-primary" type="button" onclick={() => onSaveSync(draftStrategy, draftRemote, draftUpstream)} disabled={isBusy}><Save size={14} /> {de ? "Einstellungen speichern" : "Save settings"}</button></div></footer>
  </div>
</div>
