<script setup lang="ts">
import { Dialog, InputText, Select, Textarea, InputGroup, InputGroupAddon, ToggleSwitch, Tag, Button } from 'primevue'

const props = defineProps<{
  visible: boolean
  host: any | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', val: boolean): void
  (e: 'saved'): void
}>()

const connections = useConnectionStore()
const auth = useAuthStore()

const form = ref({
  name: '',
  hostname: '',
  port: 22,
  protocol: 'ssh' as 'ssh' | 'rdp',
  groupId: null as number | null,
  credentialId: null as number | null,
  tags: [] as string[],
  notes: '',
  color: '',
})

const tagInput = ref('')
const saving = ref(false)
const error = ref('')

const isEdit = computed(() => !!props.host?.id)
const title = computed(() => isEdit.value ? 'Edit Host' : 'New Host')

const protocolOptions = [
  { label: 'SSH', value: 'ssh' },
  { label: 'RDP', value: 'rdp' },
]

const groupOptions = computed(() => [
  { label: 'No Group', value: null },
  ...connections.groups.map((g: any) => ({ label: g.name, value: g.id })),
])

// Load credentials for dropdown
const credentials = ref<any[]>([])
const credentialOptions = computed(() => [
  { label: 'No Credential', value: null },
  ...credentials.value.map((c: any) => ({ label: c.name, value: c.id })),
])

async function loadCredentials() {
  try {
    credentials.value = await $fetch('/api/credentials', {
      headers: { Authorization: `Bearer ${auth.token}` },
    })
  } catch {
    credentials.value = []
  }
}

watch(() => props.visible, (v) => {
  if (v) {
    loadCredentials()
    if (props.host?.id) {
      // Edit mode — populate form
      form.value = {
        name: props.host.name || '',
        hostname: props.host.hostname || '',
        port: props.host.port || 22,
        protocol: props.host.protocol || 'ssh',
        groupId: props.host.groupId ?? null,
        credentialId: props.host.credentialId ?? null,
        tags: [...(props.host.tags || [])],
        notes: props.host.notes || '',
        color: props.host.color || '',
      }
    } else {
      // New host — reset with optional groupId pre-fill
      form.value = {
        name: '',
        hostname: '',
        port: props.host?.groupId ? 22 : 22,
        protocol: 'ssh',
        groupId: props.host?.groupId ?? null,
        credentialId: null,
        tags: [],
        notes: '',
        color: '',
      }
    }
    error.value = ''
  }
})

// Auto-set default port when protocol changes
watch(() => form.value.protocol, (proto) => {
  if (proto === 'rdp' && form.value.port === 22) form.value.port = 3389
  if (proto === 'ssh' && form.value.port === 3389) form.value.port = 22
})

function addTag() {
  const t = tagInput.value.trim()
  if (t && !form.value.tags.includes(t)) {
    form.value.tags.push(t)
  }
  tagInput.value = ''
}

function removeTag(tag: string) {
  form.value.tags = form.value.tags.filter((t) => t !== tag)
}

async function save() {
  error.value = ''
  saving.value = true
  try {
    const payload = {
      ...form.value,
      port: Number(form.value.port),
      color: form.value.color || undefined,
      notes: form.value.notes || undefined,
    }

    if (isEdit.value) {
      await connections.updateHost(props.host.id, payload)
    } else {
      await connections.createHost(payload)
    }

    emit('saved')
    emit('update:visible', false)
  } catch (e: any) {
    error.value = e.data?.message || 'Failed to save host'
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <Dialog
    :visible="visible"
    @update:visible="emit('update:visible', $event)"
    :header="title"
    :modal="true"
    :closable="true"
    :style="{ width: '480px' }"
    class="bg-gray-900"
  >
    <div class="space-y-4 pt-2">
      <!-- Name -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Name *</label>
        <InputText v-model="form.name" placeholder="My Server" class="w-full" />
      </div>

      <!-- Hostname + Port -->
      <div class="flex gap-3">
        <div class="flex-1">
          <label class="block text-sm text-gray-400 mb-1">Hostname / IP *</label>
          <InputText v-model="form.hostname" placeholder="192.168.1.1" class="w-full" />
        </div>
        <div class="w-24">
          <label class="block text-sm text-gray-400 mb-1">Port</label>
          <InputText v-model.number="form.port" type="number" class="w-full" />
        </div>
      </div>

      <!-- Protocol -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Protocol</label>
        <Select v-model="form.protocol" :options="protocolOptions" optionLabel="label" optionValue="value" class="w-full" />
      </div>

      <!-- Group -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Group</label>
        <Select v-model="form.groupId" :options="groupOptions" optionLabel="label" optionValue="value" class="w-full" />
      </div>

      <!-- Credential -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Credential</label>
        <Select v-model="form.credentialId" :options="credentialOptions" optionLabel="label" optionValue="value" class="w-full" />
      </div>

      <!-- Color -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Color (optional)</label>
        <div class="flex items-center gap-2">
          <input v-model="form.color" type="color" class="h-8 w-12 rounded cursor-pointer bg-gray-800 border-0" />
          <span class="text-xs text-gray-500">{{ form.color || 'None' }}</span>
          <button v-if="form.color" @click="form.color = ''" class="text-xs text-gray-600 hover:text-red-400">Clear</button>
        </div>
      </div>

      <!-- Tags -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Tags</label>
        <div class="flex gap-2 mb-2">
          <InputText
            v-model="tagInput"
            placeholder="Add tag..."
            class="flex-1 text-sm"
            @keydown.enter.prevent="addTag"
          />
          <button @click="addTag" class="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-sm rounded text-gray-300">Add</button>
        </div>
        <div class="flex flex-wrap gap-1">
          <span
            v-for="tag in form.tags"
            :key="tag"
            class="inline-flex items-center gap-1 bg-gray-800 text-gray-300 text-xs px-2 py-1 rounded"
          >
            {{ tag }}
            <button @click="removeTag(tag)" class="text-gray-500 hover:text-red-400">&times;</button>
          </span>
        </div>
      </div>

      <!-- Notes -->
      <div>
        <label class="block text-sm text-gray-400 mb-1">Notes</label>
        <Textarea v-model="form.notes" rows="3" class="w-full text-sm" placeholder="Optional notes..." />
      </div>

      <!-- Error -->
      <p v-if="error" class="text-red-400 text-sm">{{ error }}</p>
    </div>

    <template #footer>
      <div class="flex justify-end gap-2">
        <Button label="Cancel" severity="secondary" @click="emit('update:visible', false)" />
        <Button :label="saving ? 'Saving...' : 'Save'" :disabled="saving || !form.name || !form.hostname" @click="save" />
      </div>
    </template>
  </Dialog>
</template>
