<script lang="ts">
  import { invoke } from "@tauri-apps/api/core";
  import { get } from "svelte/store";
  import { claudeStore, hasPermissionPending } from "$lib/stores/claude";
  import { characterState } from "$lib/stores/character";
  import type { PermissionRequest } from "$lib/types/messages";

  let isVisible = $state(false);
  let permission: PermissionRequest | null = $state(null);
  let grantedToolsList: string[] = $state([]);
  let workingDirectory = $state("");

  hasPermissionPending.subscribe((pending) => {
    isVisible = pending;
  });

  claudeStore.pendingPermission.subscribe((perm) => {
    permission = perm;
    if (perm) {
      characterState.setState("permission");
    }
  });

  claudeStore.grantedTools.subscribe((tools) => {
    grantedToolsList = Array.from(tools);
  });

  claudeStore.currentWorkingDirectory.subscribe((dir) => {
    workingDirectory = dir;
  });

  async function handleApproveAndReconnect() {
    if (permission) {
      // Capture conversation history before clearing/reconnecting
      const conversationHistory = claudeStore.getConversationHistory();
      const approvedTool = permission.tool;
      const toolInput = permission.input;

      claudeStore.grantTool(approvedTool);
      const newGrantedTools = [...grantedToolsList, approvedTool];
      claudeStore.addLine(
        "system",
        `Permission granted for: ${approvedTool}. Reconnecting with context...`
      );
      claudeStore.clearPermission();

      // Stop current session and reconnect with new permissions
      try {
        const conversationId = get(claudeStore.activeConversationId);
        if (!conversationId) {
          throw new Error("No active conversation");
        }

        await invoke("stop_claude", { conversationId });

        // Small delay to ensure clean shutdown
        await new Promise((resolve) => setTimeout(resolve, 500));

        await invoke("start_claude", {
          conversationId,
          options: {
            working_dir: workingDirectory || "/home/naomi",
            allowed_tools: newGrantedTools,
          },
        });

        // Wait for connection to establish
        await new Promise((resolve) => setTimeout(resolve, 1000));

        // Send conversation context to restore state
        if (conversationHistory) {
          const contextMessage = `[CONTEXT RESTORATION]
I just granted you permission to use the ${approvedTool} tool. Here's our conversation so far:

${conversationHistory}

The last action that was blocked was: ${approvedTool} with input:
${JSON.stringify(toolInput, null, 2)}

Please continue where we left off and retry that action now that you have permission.`;

          await invoke("send_prompt", {
            conversationId,
            message: contextMessage,
          });
        }
      } catch (error) {
        console.error("Failed to reconnect:", error);
        claudeStore.addLine("error", `Reconnect failed: ${error}`);
      }
    }
    characterState.setTemporaryState("success", 2000);
  }

  function handleDismiss() {
    claudeStore.clearPermission();
    claudeStore.addLine("system", "Permission request dismissed");
    characterState.setTemporaryState("idle", 1000);
  }

  function formatInput(input: Record<string, unknown>): string {
    try {
      return JSON.stringify(input, null, 2);
    } catch {
      return String(input);
    }
  }

  function isToolAlreadyGranted(toolName: string): boolean {
    return grantedToolsList.includes(toolName);
  }

  function handleKeydown(event: KeyboardEvent) {
    if (!isVisible || !permission) return;

    if (event.key === "Enter") {
      event.preventDefault();
      handleApproveAndReconnect();
    } else if (event.key === "Escape") {
      event.preventDefault();
      handleDismiss();
    }
  }
</script>

<svelte:window onkeydown={handleKeydown} />

{#if isVisible && permission}
  <div
    class="permission-overlay fixed inset-0 bg-black/70 flex items-center justify-center z-50 backdrop-blur-sm"
  >
    <div
      class="permission-modal bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-xl p-6 max-w-md w-full mx-4 shadow-2xl"
    >
      <div class="flex items-center gap-3 mb-4">
        <div class="w-10 h-10 rounded-full bg-yellow-500/20 flex items-center justify-center">
          <span class="text-xl">🔐</span>
        </div>
        <div>
          <h2 class="text-lg font-semibold text-[var(--text-primary)]">Permission Blocked</h2>
          <p class="text-sm text-[var(--text-secondary)]">Hikari tried to use a restricted tool</p>
        </div>
      </div>

      <div class="mb-4 px-3 py-2 bg-amber-500/10 border border-amber-500/30 rounded-md">
        <p class="text-sm text-amber-300">
          This action was automatically blocked. Approve to allow this tool for future requests.
        </p>
      </div>

      <div class="mb-4">
        <div class="text-sm text-[var(--text-secondary)] mb-1">Tool</div>
        <div
          class="px-3 py-2 bg-[var(--bg-secondary)] rounded-md text-[var(--accent-primary)] font-mono flex items-center justify-between"
        >
          <span>{permission.tool}</span>
          {#if isToolAlreadyGranted(permission.tool)}
            <span class="text-xs text-green-400 bg-green-500/20 px-2 py-0.5 rounded"
              >Already Granted</span
            >
          {/if}
        </div>
      </div>

      <div class="mb-4">
        <div class="text-sm text-[var(--text-secondary)] mb-1">Description</div>
        <div class="px-3 py-2 bg-[var(--bg-secondary)] rounded-md text-[var(--text-primary)]">
          {permission.description}
        </div>
      </div>

      {#if Object.keys(permission.input).length > 0}
        <div class="mb-6">
          <div class="text-sm text-[var(--text-secondary)] mb-1">Details</div>
          <pre
            class="px-3 py-2 bg-[var(--bg-terminal)] rounded-md text-[var(--text-primary)] text-xs overflow-x-auto max-h-32">{formatInput(
              permission.input
            )}</pre>
        </div>
      {/if}

      <div class="flex gap-3">
        <button
          onclick={handleDismiss}
          class="flex-1 px-4 py-2 bg-gray-500/20 hover:bg-gray-500/30 text-[var(--text-secondary)] rounded-lg transition-colors font-medium"
        >
          Dismiss
        </button>
        <button
          onclick={handleApproveAndReconnect}
          class="flex-1 px-4 py-2 bg-green-500/20 hover:bg-green-500/30 text-green-400 rounded-lg transition-colors font-medium"
        >
          Allow & Reconnect
        </button>
      </div>
    </div>
  </div>
{/if}
