<template>
  <div class="flex flex-col h-full">
    <LayoutHeader :title="$t('apps.title')">
      <template #right>
        <Button variant="subtle" @click="refreshData" :loading="apps.loading">
          <template #prefix>
            <FeatherIcon name="refresh-cw" class="h-4 w-4" />
          </template>
          {{ $t('common.refresh') }}
        </Button>
        <Button variant="solid" @click="showCreateModal = true">
          <template #prefix>
            <FeatherIcon name="plus" class="h-4 w-4" />
          </template>
          {{ $t('apps.createApp') || 'Create App' }}
        </Button>
      </template>
    </LayoutHeader>

    <div class="flex-1 overflow-auto p-5">
      <div v-if="apps.loading" class="flex items-center justify-center h-64">
        <Spinner class="h-8 w-8" />
      </div>

      <div v-else-if="appsList.length" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <div
          v-for="app in appsList"
          :key="app.id"
          class="rounded-lg border p-5 hover:shadow-md transition-shadow cursor-pointer"
          @click="goToApp(app.id)"
        >
          <div class="flex items-start justify-between mb-4">
            <div class="flex items-center gap-3">
              <div class="w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center">
                <FeatherIcon name="package" class="h-6 w-6 text-blue-600" />
              </div>
              <div>
                <h3 class="text-base font-medium text-ink-gray-9">
                  {{ app.name }}
                </h3>
                <Badge
                  class="mt-1"
                  :variant="app.status === 'active' ? 'success' : 'warning'"
                  :label="app.status"
                />
              </div>
            </div>
            <Dropdown
              :options="getAppActions(app)"
              @click.stop
            >
              <Button variant="ghost" size="sm">
                <FeatherIcon name="more-vertical" class="h-4 w-4" />
              </Button>
            </Dropdown>
          </div>

          <p class="text-sm text-ink-gray-5 mb-4 line-clamp-2">
            {{ app.description }}
          </p>

          <div class="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span class="text-ink-gray-4 text-xs">{{ $t('apps.imageVersion') }}</span>
              <p class="font-medium text-ink-gray-9">{{ app.currentVersion || '-' }}</p>
            </div>
            <div>
              <span class="text-ink-gray-4 text-xs">Versions</span>
              <p class="font-medium text-ink-gray-9">{{ app.versions_count || 0 }}</p>
            </div>
          </div>

          <div class="mt-4 pt-4 border-t flex justify-between items-center text-xs text-ink-gray-4">
            <span>{{ app.size || '-' }}</span>
            <span>Updated: {{ app.lastUpdated || '-' }}</span>
          </div>
        </div>
      </div>

      <EmptyState
        v-else
        icon="package"
        :title="$t('apps.noApps')"
        description="No app templates found. Create one to get started."
      >
        <template #action>
          <Button variant="solid" @click="showCreateModal = true">
            {{ $t('apps.createApp') || 'Create App' }}
          </Button>
        </template>
      </EmptyState>
    </div>

    <!-- Create App Modal -->
    <Dialog v-model="showCreateModal" :options="{ title: 'Create App Template' }">
      <template #body-content>
        <div class="space-y-4">
          <FormControl
            v-model="newApp.name"
            label="App Name"
            type="text"
            placeholder="my-app"
            :description="'Alphanumeric characters, dashes and underscores only'"
          />
          <FormControl
            v-model="newApp.description"
            label="Description"
            type="textarea"
            placeholder="Description of this app template..."
          />
          <div>
            <label class="block text-sm font-medium text-ink-gray-7 mb-1">
              YAML Configuration
            </label>
            <textarea
              v-model="newApp.yaml_content"
              class="w-full h-64 bg-gray-900 text-gray-100 p-4 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="# Distrobuilder YAML configuration..."
            ></textarea>
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showCreateModal = false">
          {{ $t('common.cancel') }}
        </Button>
        <Button
          variant="solid"
          @click="createApp"
          :loading="creating"
          :disabled="!newApp.name"
        >
          {{ $t('common.create') }}
        </Button>
      </template>
    </Dialog>

    <!-- Delete Confirmation Modal -->
    <Dialog v-model="showDeleteModal" :options="{ title: 'Delete App Template' }">
      <template #body-content>
        <p class="text-sm text-ink-gray-7">
          Are you sure you want to delete <strong>{{ appToDelete?.name }}</strong>?
          This will only delete the template file, not the built images.
        </p>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showDeleteModal = false">
          {{ $t('common.cancel') }}
        </Button>
        <Button variant="solid" theme="red" @click="confirmDelete" :loading="deleting">
          Delete
        </Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
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 router = useRouter()

const showCreateModal = ref(false)
const showDeleteModal = ref(false)
const creating = ref(false)
const deleting = ref(false)
const appToDelete = ref(null)

const defaultYamlTemplate = `image:
  distribution: "alpinelinux"

source:
  downloader: alpinelinux-http
  same_as: 3.12
  url: https://mirror.csclub.uwaterloo.ca/alpine/

targets:
  incus:
    vm:
      filesystem: ext4

files:
- path: /etc/hostname
  generator: hostname

- path: /etc/hosts
  generator: hosts

- path: /etc/network/interfaces
  generator: dump
  content: |-
    auto eth0
    iface eth0 inet dhcp

packages:
  manager: apk
  update: true
  cleanup: true
  sets:
  - packages:
    - alpine-base
    action: install

actions:
- trigger: post-packages
  action: |-
    #!/bin/sh
    set -eux
    rm -f /var/cache/apk/*
`

const newApp = ref({
  name: '',
  description: '',
  yaml_content: defaultYamlTemplate,
})

const apps = createResource({
  url: 'admin_panel.api.apps.get_apps',
  auto: true,
})

const appsList = computed(() => apps.data || [])

function refreshData() {
  apps.reload()
}

function goToApp(appId) {
  router.push({ name: 'AppDetail', params: { appId } })
}

function getAppActions(app) {
  return [
    {
      label: 'View Details',
      icon: 'eye',
      onClick: () => goToApp(app.id),
    },
    {
      label: 'Delete',
      icon: 'trash-2',
      onClick: () => {
        appToDelete.value = app
        showDeleteModal.value = true
      },
    },
  ]
}

async function createApp() {
  if (!newApp.value.name) {
    console.error('App name is required')
    return
  }

  creating.value = true
  try {
    const result = await call('admin_panel.api.apps.create_app', {
      app_name: newApp.value.name,
      description: newApp.value.description,
      yaml_content: newApp.value.yaml_content,
    })

    if (result.success) {
      console.log(result.message)
      showCreateModal.value = false
      newApp.value = {
        name: '',
        description: '',
        yaml_content: defaultYamlTemplate,
      }
      apps.reload()
    } else {
      console.error(result.error || 'Failed to create app')
    }
  } catch (error) {
    console.error(error.message || 'Failed to create app')
  } finally {
    creating.value = false
  }
}

async function confirmDelete() {
  if (!appToDelete.value) return

  deleting.value = true
  try {
    const result = await call('admin_panel.api.apps.delete_app', {
      app_name: appToDelete.value.id,
    })

    if (result.success) {
      console.log(result.message)
      showDeleteModal.value = false
      appToDelete.value = null
      apps.reload()
    } else {
      console.error(result.error || 'Failed to delete app')
    }
  } catch (error) {
    console.error(error.message || 'Failed to delete app')
  } finally {
    deleting.value = false
  }
}
</script>
