<template>
  <div class="flex flex-col h-full">
    <LayoutHeader :title="$t('servers.title')">
      <template #right>
        <Button variant="subtle" @click="refreshData" :loading="refreshing">
          <template #prefix>
            <FeatherIcon name="refresh-cw" class="h-4 w-4" />
          </template>
          {{ $t('common.refresh') }}
        </Button>
        <Button variant="solid" @click="showAddServerModal = true" :disabled="!certStatus?.has_certificate">
          <template #prefix>
            <FeatherIcon name="plus" class="h-4 w-4" />
          </template>
          {{ $t('servers.addServer') }}
        </Button>
      </template>
    </LayoutHeader>

    <div class="flex-1 overflow-auto p-5 space-y-6">
      <!-- Section 1: Certificate Setup -->
      <div class="rounded-lg border p-5">
        <div class="flex items-center justify-between mb-4">
          <div>
            <h3 class="text-base font-medium text-ink-gray-9">
              Panel Certificate
            </h3>
            <p class="text-sm text-ink-gray-5 mt-1">
              Client certificate used to authenticate with Incus servers
            </p>
          </div>
        </div>

        <div v-if="certStatusRes.loading" class="flex justify-center py-4">
          <Spinner class="h-6 w-6" />
        </div>

        <div v-else>
          <!-- Certificate exists -->
          <div v-if="certStatus?.has_certificate" class="space-y-4">
            <div class="flex items-center gap-3 p-3 rounded-lg bg-green-50">
              <div class="w-10 h-10 rounded-full flex items-center justify-center bg-green-100">
                <FeatherIcon name="shield" class="h-5 w-5 text-green-600" />
              </div>
              <div class="flex-1">
                <p class="text-sm font-medium text-green-800">Certificate configured</p>
                <p class="text-xs text-green-600 font-mono">{{ certStatus.cert_path }}</p>
              </div>
              <Button variant="subtle" size="sm" @click="showCertModal = true">
                <template #prefix>
                  <FeatherIcon name="eye" class="h-4 w-4" />
                </template>
                View
              </Button>
            </div>

            <div class="bg-blue-50 rounded-lg p-4">
              <p class="text-sm text-blue-800 font-medium mb-2">How to trust this certificate on Incus servers:</p>
              <ol class="text-sm text-blue-700 space-y-1 list-decimal list-inside">
                <li>Click "View" to copy the certificate content</li>
                <li>Save it as <code class="bg-blue-100 px-1 rounded">admin-panel.crt</code> on your Incus server</li>
                <li>Run: <code class="bg-blue-100 px-1 rounded">incus config trust add-certificate admin-panel.crt</code></li>
              </ol>
            </div>
          </div>

          <!-- No certificate -->
          <div v-else class="space-y-4">
            <div class="flex items-center gap-3 p-3 rounded-lg bg-yellow-50">
              <div class="w-10 h-10 rounded-full flex items-center justify-center bg-yellow-100">
                <FeatherIcon name="alert-circle" class="h-5 w-5 text-yellow-600" />
              </div>
              <div class="flex-1">
                <p class="text-sm font-medium text-yellow-800">No certificate</p>
                <p class="text-xs text-yellow-600">Generate a client certificate to connect to Incus servers</p>
              </div>
              <Button variant="solid" @click="generateCertificate" :loading="generating">
                <template #prefix>
                  <FeatherIcon name="key" class="h-4 w-4" />
                </template>
                Generate Certificate
              </Button>
            </div>
          </div>
        </div>
      </div>

      <!-- Section 2: Distrobuilder Setup -->
      <div class="rounded-lg border p-5">
        <div class="flex items-center justify-between mb-4">
          <div>
            <h3 class="text-base font-medium text-ink-gray-9">
              {{ $t('servers.setup.title') }}
            </h3>
            <p class="text-sm text-ink-gray-5 mt-1">
              Tools needed for building container images
            </p>
          </div>
          <Button
            variant="solid"
            @click="showInstallModal = true"
            :disabled="setupStatus?.distrobuilder_installed"
          >
            <template #prefix>
              <FeatherIcon name="download" class="h-4 w-4" />
            </template>
            {{ $t('servers.setup.install') }}
          </Button>
        </div>

        <div v-if="setupStatusRes.loading" class="flex justify-center py-4">
          <Spinner class="h-6 w-6" />
        </div>

        <div v-else class="flex items-center gap-3 p-3 rounded-lg bg-surface-gray-1">
          <div
            class="w-10 h-10 rounded-full flex items-center justify-center"
            :class="setupStatus?.distrobuilder_installed ? 'bg-green-100' : 'bg-red-100'"
          >
            <FeatherIcon
              :name="setupStatus?.distrobuilder_installed ? 'check' : 'x'"
              class="h-5 w-5"
              :class="setupStatus?.distrobuilder_installed ? 'text-green-600' : 'text-red-600'"
            />
          </div>
          <div>
            <p class="text-sm font-medium text-ink-gray-9">
              {{ $t('servers.setup.distrobuilderInstalled') }}
            </p>
            <p class="text-xs text-ink-gray-5">For building custom images</p>
          </div>
        </div>
      </div>

      <!-- Section 3: Remote Servers -->
      <div class="rounded-lg border p-5">
        <div class="flex items-center justify-between mb-4">
          <div>
            <h3 class="text-base font-medium text-ink-gray-9">
              {{ $t('servers.remoteServers') }}
            </h3>
            <p class="text-sm text-ink-gray-5 mt-1">
              {{ $t('servers.roles.title') }}
            </p>
          </div>
        </div>

        <div v-if="serversRes.loading" class="flex justify-center py-8">
          <Spinner class="h-8 w-8" />
        </div>

        <div v-else-if="serversList.length" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <div
            v-for="server in serversList"
            :key="server.name"
            class="rounded-lg border p-4 hover:shadow-md transition-shadow"
          >
            <div class="flex items-start justify-between mb-3">
              <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                  <FeatherIcon name="cloud" class="h-5 w-5 text-blue-600" />
                </div>
                <div>
                  <h4 class="text-sm font-medium text-ink-gray-9">{{ server.name }}</h4>
                  <Badge
                    class="mt-1"
                    :variant="getStatusVariant(server.status)"
                    :label="getStatusLabel(server.status)"
                  />
                </div>
              </div>
              <Dropdown :options="getServerActions(server)" @click.stop>
                <Button variant="ghost" size="sm">
                  <FeatherIcon name="more-vertical" class="h-4 w-4" />
                </Button>
              </Dropdown>
            </div>

            <div class="text-xs text-ink-gray-5 mb-3 truncate" :title="server.url">
              {{ server.url }}
            </div>

            <!-- Roles -->
            <div class="space-y-2">
              <label class="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  :checked="server.is_image_server"
                  @change="updateServerRole(server.name, 'is_image_server', $event.target.checked)"
                  class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span class="text-sm text-ink-gray-7">{{ $t('servers.roles.imageServer') }}</span>
              </label>
              <label class="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  :checked="server.is_container_server"
                  @change="updateServerRole(server.name, 'is_container_server', $event.target.checked)"
                  class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span class="text-sm text-ink-gray-7">{{ $t('servers.roles.containerServer') }}</span>
              </label>
            </div>
          </div>
        </div>

        <EmptyState
          v-else
          icon="cloud"
          :title="$t('servers.noServers')"
          :description="certStatus?.has_certificate ? $t('servers.addFirst') : 'Generate a certificate first to add servers'"
        >
          <template #action>
            <Button
              v-if="certStatus?.has_certificate"
              variant="solid"
              @click="showAddServerModal = true"
            >
              {{ $t('servers.addServer') }}
            </Button>
            <Button
              v-else
              variant="solid"
              @click="generateCertificate"
              :loading="generating"
            >
              Generate Certificate
            </Button>
          </template>
        </EmptyState>
      </div>
    </div>

    <!-- Install Modal -->
    <Dialog v-model="showInstallModal" :options="{ title: $t('servers.setup.title') }">
      <template #body-content>
        <div class="space-y-4">
          <p class="text-sm text-ink-gray-7">
            Install distrobuilder for building custom container images.
          </p>
          <FormControl
            v-model="doasPassword"
            :label="$t('servers.setup.doasPassword')"
            type="password"
            placeholder="********"
            :description="$t('servers.setup.doasPasswordDesc')"
          />
          <div v-if="installResult" class="mt-4">
            <label class="block text-sm font-medium text-ink-gray-7 mb-2">Output</label>
            <div class="bg-gray-900 text-gray-100 p-4 rounded-lg text-xs font-mono max-h-64 overflow-y-auto">
              <div
                v-for="(log, index) in installResult.logs"
                :key="index"
                :class="{
                  'text-green-400': log.includes('Done'),
                  'text-red-400': log.includes('Failed'),
                  'text-yellow-400': log.includes('==='),
                }"
              >
                {{ log }}
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="closeInstallModal">
          {{ installResult ? $t('common.close') : $t('common.cancel') }}
        </Button>
        <Button
          v-if="!installResult"
          variant="solid"
          @click="runInstall"
          :loading="installing"
          :disabled="!doasPassword"
        >
          <template #prefix>
            <FeatherIcon name="download" class="h-4 w-4" />
          </template>
          {{ $t('servers.setup.install') }}
        </Button>
      </template>
    </Dialog>

    <!-- Add Server Modal -->
    <Dialog v-model="showAddServerModal" :options="{ title: $t('servers.addServer') }">
      <template #body-content>
        <div class="space-y-4">
          <FormControl
            v-model="newServer.name"
            :label="$t('servers.serverName')"
            type="text"
            placeholder="production"
            description="Alphanumeric, dashes and underscores only"
          />
          <FormControl
            v-model="newServer.url"
            :label="$t('servers.serverUrl')"
            type="text"
            placeholder="https://192.168.1.100:8443"
          />

          <div class="space-y-2">
            <label class="block text-sm font-medium text-ink-gray-7">
              {{ $t('servers.roles.title') }}
            </label>
            <label class="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                v-model="newServer.is_image_server"
                class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span class="text-sm text-ink-gray-7">{{ $t('servers.roles.imageServer') }}</span>
            </label>
            <label class="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                v-model="newServer.is_container_server"
                class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span class="text-sm text-ink-gray-7">{{ $t('servers.roles.containerServer') }}</span>
            </label>
          </div>

          <div v-if="addServerError" class="text-sm text-red-500 bg-red-50 p-2 rounded">
            {{ addServerError }}
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="closeAddServerModal">
          {{ $t('common.cancel') }}
        </Button>
        <Button
          variant="solid"
          @click="addServer"
          :loading="addingServer"
          :disabled="!newServer.name || !newServer.url"
        >
          {{ $t('common.create') }}
        </Button>
      </template>
    </Dialog>

    <!-- Remove Server Confirmation Modal -->
    <Dialog v-model="showRemoveModal" :options="{ title: $t('servers.removeServer') }">
      <template #body-content>
        <p class="text-sm text-ink-gray-7">
          Are you sure you want to remove <strong>{{ serverToRemove?.name }}</strong>?
        </p>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showRemoveModal = false">
          {{ $t('common.cancel') }}
        </Button>
        <Button variant="solid" theme="red" @click="confirmRemove" :loading="removingServer">
          {{ $t('common.delete') }}
        </Button>
      </template>
    </Dialog>

    <!-- Certificate View Modal -->
    <Dialog v-model="showCertModal" :options="{ title: 'Panel Certificate', size: 'lg' }">
      <template #body-content>
        <div class="space-y-4">
          <p class="text-sm text-ink-gray-7">
            Copy this certificate and add it to your Incus servers' trust store.
          </p>

          <div v-if="certContentRes.loading" class="flex justify-center py-8">
            <Spinner class="h-8 w-8" />
          </div>

          <div v-else-if="certContent" class="space-y-4">
            <div class="relative">
              <textarea
                :value="certContent.certificate"
                readonly
                class="w-full h-48 rounded-lg border border-gray-300 px-3 py-2 text-xs font-mono bg-gray-50"
              ></textarea>
              <Button
                variant="subtle"
                size="sm"
                class="absolute top-2 right-2"
                @click="copyCertificate"
              >
                <template #prefix>
                  <FeatherIcon :name="copied ? 'check' : 'copy'" class="h-4 w-4" />
                </template>
                {{ copied ? 'Copied!' : 'Copy' }}
              </Button>
            </div>

            <div class="bg-blue-50 rounded-lg p-4">
              <p class="text-sm text-blue-800 font-medium mb-2">On your Incus server:</p>
              <code class="text-sm text-blue-700 block bg-blue-100 p-2 rounded">
                incus config trust add-certificate admin-panel.crt
              </code>
            </div>
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showCertModal = false">
          {{ $t('common.close') }}
        </Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { createResource, call, Button, Badge, FormControl, Dialog, Spinner, FeatherIcon, Dropdown } from 'frappe-ui'
import LayoutHeader from '@/components/Common/LayoutHeader.vue'
import EmptyState from '@/components/Common/EmptyState.vue'

const refreshing = ref(false)
const showInstallModal = ref(false)
const showAddServerModal = ref(false)
const showRemoveModal = ref(false)
const showCertModal = ref(false)
const serverToRemove = ref(null)

const doasPassword = ref('')
const installing = ref(false)
const installResult = ref(null)

const addingServer = ref(false)
const removingServer = ref(false)
const generating = ref(false)
const copied = ref(false)

const addServerError = ref('')

const newServer = ref({
  name: '',
  url: '',
  is_image_server: false,
  is_container_server: false,
})

// Resources
const certStatusRes = createResource({
  url: 'admin_panel.api.servers.get_certificate_status',
  auto: true,
})

const setupStatusRes = createResource({
  url: 'admin_panel.api.servers.get_setup_status',
  auto: true,
})

const serversRes = createResource({
  url: 'admin_panel.api.servers.get_servers',
  auto: true,
})

const certContentRes = createResource({
  url: 'admin_panel.api.servers.get_client_certificate',
})

const certStatus = computed(() => certStatusRes.data)
const setupStatus = computed(() => setupStatusRes.data)
const serversList = computed(() => serversRes.data || [])
const certContent = computed(() => certContentRes.data)

// Load certificate content when modal opens
watch(showCertModal, (show) => {
  if (show && !certContentRes.data) {
    certContentRes.fetch()
  }
})

function refreshData() {
  refreshing.value = true
  Promise.all([
    certStatusRes.reload(),
    setupStatusRes.reload(),
    serversRes.reload(),
  ]).finally(() => {
    refreshing.value = false
  })
}

function getStatusVariant(status) {
  switch (status) {
    case 'online':
      return 'success'
    case 'offline':
    case 'error':
      return 'error'
    case 'timeout':
    case 'no_cert':
      return 'orange'
    default:
      return 'subtle'
  }
}

function getStatusLabel(status) {
  switch (status) {
    case 'online':
      return 'Online'
    case 'offline':
      return 'Offline'
    case 'timeout':
      return 'Timeout'
    case 'no_cert':
      return 'Not Trusted'
    case 'error':
      return 'Error'
    default:
      return 'Unknown'
  }
}

function getServerActions(server) {
  return [
    {
      label: 'Test Connection',
      icon: 'wifi',
      onClick: () => testServerConnection(server.name),
    },
    {
      label: 'Remove',
      icon: 'trash-2',
      onClick: () => {
        serverToRemove.value = server
        showRemoveModal.value = true
      },
    },
  ]
}

async function generateCertificate() {
  generating.value = true

  try {
    const result = await call('admin_panel.api.servers.generate_client_certificate')

    if (result.success) {
      certStatusRes.reload()
    } else {
      console.error(result.error || 'Failed to generate certificate')
    }
  } catch (error) {
    console.error(error.message || 'Failed to generate certificate')
  } finally {
    generating.value = false
  }
}

function copyCertificate() {
  if (certContent.value?.certificate) {
    navigator.clipboard.writeText(certContent.value.certificate)
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  }
}

async function runInstall() {
  installing.value = true
  installResult.value = null

  try {
    const result = await call('admin_panel.api.servers.run_setup', {
      doas_password: doasPassword.value,
    })
    installResult.value = result

    if (result.success) {
      setupStatusRes.reload()
    }
  } catch (error) {
    installResult.value = {
      success: false,
      logs: [`Error: ${error.message}`],
    }
  } finally {
    installing.value = false
  }
}

function closeInstallModal() {
  showInstallModal.value = false
  doasPassword.value = ''
  installResult.value = null
}

async function testServerConnection(serverName) {
  try {
    const result = await call('admin_panel.api.servers.test_connection', {
      name: serverName,
    })

    if (result.success) {
      console.log(`${serverName}: Connection successful`)
    } else {
      console.error(`${serverName}: ${result.message}`)
    }

    serversRes.reload()
  } catch (error) {
    console.error(error.message || 'Connection test failed')
  }
}

function closeAddServerModal() {
  showAddServerModal.value = false
  addServerError.value = ''
  newServer.value = {
    name: '',
    url: '',
    is_image_server: false,
    is_container_server: false,
  }
}

async function addServer() {
  addingServer.value = true
  addServerError.value = ''

  try {
    const result = await call('admin_panel.api.servers.add_server', {
      name: newServer.value.name,
      url: newServer.value.url,
      is_image_server: newServer.value.is_image_server,
      is_container_server: newServer.value.is_container_server,
    })

    if (!result.success) {
      addServerError.value = result.error || 'Failed to add server'
      return
    }

    closeAddServerModal()
    serversRes.reload()
  } catch (error) {
    addServerError.value = error.message || error.exc || 'Failed to add server'
  } finally {
    addingServer.value = false
  }
}

async function confirmRemove() {
  if (!serverToRemove.value) return

  removingServer.value = true

  try {
    const result = await call('admin_panel.api.servers.remove_server', {
      name: serverToRemove.value.name,
    })

    if (result.success) {
      console.log(result.message)
      showRemoveModal.value = false
      serverToRemove.value = null
      serversRes.reload()
    } else {
      console.error(result.error || 'Failed to remove server')
    }
  } catch (error) {
    console.error(error.message || 'Failed to remove server')
  } finally {
    removingServer.value = false
  }
}

async function updateServerRole(serverName, roleField, value) {
  try {
    const params = { name: serverName }
    params[roleField] = value

    const result = await call('admin_panel.api.servers.update_server', params)

    if (result.success) {
      console.log(result.message)
    } else {
      console.error(result.error || 'Failed to update server')
      serversRes.reload()
    }
  } catch (error) {
    console.error(error.message || 'Failed to update server')
    serversRes.reload()
  }
}
</script>
