<template>
  <Teleport to="body">
    <div
      v-if="visible"
      class="fixed inset-0 z-50 flex items-center justify-center"
      @click.self="close"
      @keydown.esc="close"
    >
      <!-- Backdrop -->
      <div class="absolute inset-0 bg-black/50" @click="close" />

      <!-- Dialog -->
      <div class="relative w-full max-w-md bg-[#161b22] border border-[#30363d] rounded-lg shadow-2xl overflow-hidden">
        <!-- Header -->
        <div class="flex items-center justify-between px-4 py-3 border-b border-[#30363d]">
          <h3 class="text-sm font-semibold text-[var(--wraith-text-primary)]">
            {{ isEditing ? "Edit Connection" : "New Connection" }}
          </h3>
          <button
            class="text-[var(--wraith-text-muted)] hover:text-[var(--wraith-text-primary)] transition-colors cursor-pointer"
            @click="close"
          >
            <svg class="w-4 h-4" viewBox="0 0 16 16" fill="currentColor">
              <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 1 1 1.06 1.06L9.06 8l3.22 3.22a.749.749 0 1 1-1.06 1.06L8 9.06l-3.22 3.22a.749.749 0 1 1-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z" />
            </svg>
          </button>
        </div>

        <!-- Body -->
        <div class="px-4 py-4 space-y-3 max-h-[60vh] overflow-y-auto">
          <!-- Name -->
          <div>
            <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Name</label>
            <input
              v-model="form.name"
              type="text"
              placeholder="My Server"
              class="w-full px-3 py-2 text-sm rounded bg-[#0d1117] border border-[#30363d] text-[var(--wraith-text-primary)] placeholder-[var(--wraith-text-muted)] outline-none focus:border-[var(--wraith-accent-blue)] transition-colors"
            />
          </div>

          <!-- Hostname & Port -->
          <div class="flex gap-3">
            <div class="flex-1">
              <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Hostname</label>
              <input
                v-model="form.hostname"
                type="text"
                placeholder="192.168.1.1"
                class="w-full px-3 py-2 text-sm rounded bg-[#0d1117] border border-[#30363d] text-[var(--wraith-text-primary)] placeholder-[var(--wraith-text-muted)] outline-none focus:border-[var(--wraith-accent-blue)] transition-colors"
              />
            </div>
            <div class="w-24">
              <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Port</label>
              <input
                v-model.number="form.port"
                type="number"
                class="w-full px-3 py-2 text-sm rounded bg-[#0d1117] border border-[#30363d] text-[var(--wraith-text-primary)] outline-none focus:border-[var(--wraith-accent-blue)] transition-colors"
              />
            </div>
          </div>

          <!-- Protocol -->
          <div>
            <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Protocol</label>
            <div class="flex gap-2">
              <button
                class="flex-1 py-2 text-sm rounded border transition-colors cursor-pointer"
                :class="form.protocol === 'ssh'
                  ? 'bg-[#3fb950]/10 border-[#3fb950] text-[#3fb950]'
                  : 'bg-[#0d1117] border-[#30363d] text-[var(--wraith-text-muted)] hover:border-[var(--wraith-text-secondary)]'
                "
                @click="setProtocol('ssh')"
              >
                SSH
              </button>
              <button
                class="flex-1 py-2 text-sm rounded border transition-colors cursor-pointer"
                :class="form.protocol === 'rdp'
                  ? 'bg-[#1f6feb]/10 border-[#1f6feb] text-[#1f6feb]'
                  : 'bg-[#0d1117] border-[#30363d] text-[var(--wraith-text-muted)] hover:border-[var(--wraith-text-secondary)]'
                "
                @click="setProtocol('rdp')"
              >
                RDP
              </button>
            </div>
          </div>

          <!-- Group -->
          <div>
            <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Group</label>
            <select
              v-model="form.groupId"
              class="w-full px-3 py-2 text-sm rounded bg-[#0d1117] border border-[#30363d] text-[var(--wraith-text-primary)] outline-none focus:border-[var(--wraith-accent-blue)] transition-colors cursor-pointer"
            >
              <option :value="null">No Group</option>
              <option v-for="group in connectionStore.groups" :key="group.id" :value="group.id">
                {{ group.name }}
              </option>
            </select>
          </div>

          <!-- Tags -->
          <div>
            <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Tags (comma-separated)</label>
            <input
              v-model="tagsInput"
              type="text"
              placeholder="Prod, Linux, Web"
              class="w-full px-3 py-2 text-sm rounded bg-[#0d1117] border border-[#30363d] text-[var(--wraith-text-primary)] placeholder-[var(--wraith-text-muted)] outline-none focus:border-[var(--wraith-accent-blue)] transition-colors"
            />
          </div>

          <!-- Color -->
          <div>
            <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Color Label</label>
            <div class="flex gap-2">
              <button
                v-for="color in colorOptions"
                :key="color.value"
                class="w-6 h-6 rounded-full border-2 transition-transform cursor-pointer hover:scale-110"
                :class="form.color === color.value ? 'border-white scale-110' : 'border-transparent'"
                :style="{ backgroundColor: color.hex }"
                :title="color.label"
                @click="form.color = color.value"
              />
            </div>
          </div>

          <!-- Notes -->
          <div>
            <label class="block text-xs text-[var(--wraith-text-secondary)] mb-1">Notes</label>
            <textarea
              v-model="form.notes"
              rows="3"
              placeholder="Optional notes about this connection..."
              class="w-full px-3 py-2 text-sm rounded bg-[#0d1117] border border-[#30363d] text-[var(--wraith-text-primary)] placeholder-[var(--wraith-text-muted)] outline-none focus:border-[var(--wraith-accent-blue)] transition-colors resize-none"
            />
          </div>
        </div>

        <!-- Footer -->
        <div class="flex items-center justify-end gap-2 px-4 py-3 border-t border-[#30363d]">
          <button
            class="px-3 py-1.5 text-xs text-[var(--wraith-text-secondary)] hover:text-[var(--wraith-text-primary)] rounded border border-[#30363d] hover:bg-[#30363d] transition-colors cursor-pointer"
            @click="close"
          >
            Cancel
          </button>
          <button
            class="px-3 py-1.5 text-xs text-white bg-[#238636] hover:bg-[#2ea043] rounded transition-colors cursor-pointer"
            :class="{ 'opacity-50 cursor-not-allowed': !isValid }"
            :disabled="!isValid"
            @click="save"
          >
            {{ isEditing ? "Save Changes" : "Create" }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useConnectionStore, type Connection } from "@/stores/connection.store";

interface ConnectionForm {
  name: string;
  hostname: string;
  port: number;
  protocol: "ssh" | "rdp";
  groupId: number | null;
  color: string;
  notes: string;
}

const connectionStore = useConnectionStore();

const visible = ref(false);
const isEditing = ref(false);
const editingId = ref<number | null>(null);
const tagsInput = ref("");

const form = ref<ConnectionForm>({
  name: "",
  hostname: "",
  port: 22,
  protocol: "ssh",
  groupId: null,
  color: "",
  notes: "",
});

const colorOptions = [
  { value: "", label: "None", hex: "#30363d" },
  { value: "red", label: "Red", hex: "#f85149" },
  { value: "orange", label: "Orange", hex: "#d29922" },
  { value: "green", label: "Green", hex: "#3fb950" },
  { value: "blue", label: "Blue", hex: "#58a6ff" },
  { value: "purple", label: "Purple", hex: "#bc8cff" },
  { value: "pink", label: "Pink", hex: "#f778ba" },
];

const isValid = computed(() => {
  return form.value.name.trim() !== "" && form.value.hostname.trim() !== "" && form.value.port > 0;
});

function setProtocol(protocol: "ssh" | "rdp"): void {
  form.value.protocol = protocol;
  if (protocol === "ssh" && form.value.port === 3389) {
    form.value.port = 22;
  } else if (protocol === "rdp" && form.value.port === 22) {
    form.value.port = 3389;
  }
}

function openNew(groupId?: number): void {
  isEditing.value = false;
  editingId.value = null;
  form.value = {
    name: "",
    hostname: "",
    port: 22,
    protocol: "ssh",
    groupId: groupId ?? null,
    color: "",
    notes: "",
  };
  tagsInput.value = "";
  visible.value = true;
}

function openEdit(conn: Connection): void {
  isEditing.value = true;
  editingId.value = conn.id;
  form.value = {
    name: conn.name,
    hostname: conn.hostname,
    port: conn.port,
    protocol: conn.protocol,
    groupId: conn.groupId,
    color: "",
    notes: "",
  };
  tagsInput.value = conn.tags?.join(", ") ?? "";
  visible.value = true;
}

function close(): void {
  visible.value = false;
}

function save(): void {
  if (!isValid.value) return;

  const tags = tagsInput.value
    .split(",")
    .map((t) => t.trim())
    .filter((t) => t.length > 0);

  if (isEditing.value && editingId.value !== null) {
    // TODO: Replace with Wails binding — ConnectionService.UpdateConnection(id, input)
    const conn = connectionStore.connections.find((c) => c.id === editingId.value);
    if (conn) {
      conn.name = form.value.name;
      conn.hostname = form.value.hostname;
      conn.port = form.value.port;
      conn.protocol = form.value.protocol;
      conn.groupId = form.value.groupId ?? conn.groupId;
      conn.tags = tags;
    }
  } else {
    // TODO: Replace with Wails binding — ConnectionService.CreateConnection(input)
    const newId = Math.max(...connectionStore.connections.map((c) => c.id), 0) + 1;
    connectionStore.connections.push({
      id: newId,
      name: form.value.name,
      hostname: form.value.hostname,
      port: form.value.port,
      protocol: form.value.protocol,
      groupId: form.value.groupId ?? 1,
      tags,
    });
  }

  close();
}

defineExpose({ openNew, openEdit, close, visible });
</script>
