<template>
  <div class="flex flex-col h-full">
    <LayoutHeader title="Containers">
      <template #right>
        <Button variant="subtle" @click="fetchContainers" :loading="containersResource.loading">
          <template #prefix>
            <FeatherIcon name="refresh-cw" class="h-4 w-4" />
          </template>
          Refresh
        </Button>
        <Button variant="solid" @click="showCreateModal = true">
          <template #prefix>
            <FeatherIcon name="plus" class="h-4 w-4" />
          </template>
          New Container
        </Button>
      </template>
    </LayoutHeader>

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

      <div v-else-if="containers.length" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <SiteCard
          v-for="container in containers"
          :key="container.name"
          :site="container"
          @click="goToSite(container.name)"
        />
      </div>

      <EmptyState
        v-else
        icon="server"
        title="No containers yet"
        description="Create your first container to get started"
      >
        <template #action>
          <Button variant="solid" @click="showCreateModal = true">
            Create Container
          </Button>
        </template>
      </EmptyState>
    </div>

    <CreateSiteModal v-model="showCreateModal" @created="fetchContainers" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Button, FeatherIcon, LoadingIndicator, createResource } from 'frappe-ui'
import LayoutHeader from '@/components/Common/LayoutHeader.vue'
import EmptyState from '@/components/Common/EmptyState.vue'
import SiteCard from '@/components/Sites/SiteCard.vue'
import CreateSiteModal from '@/components/Sites/CreateSiteModal.vue'

const router = useRouter()
const showCreateModal = ref(false)
const containers = ref([])

const containersResource = createResource({
  url: 'cloud_portal.cloud_portal.doctype.cloud_container.cloud_container.get_user_containers',
  auto: false,
  onSuccess(data) {
    containers.value = data.map(c => ({
      name: c.name,
      container_name: c.container_name,
      status: c.status,
      image: c.image,
      ip_address: c.ip_address,
      created: c.creation ? new Date(c.creation).toLocaleDateString() : '',
    }))
  },
})

const loading = computed(() => containersResource.loading && containers.value.length === 0)

function fetchContainers() {
  containersResource.fetch()
}

function goToSite(siteId) {
  router.push({ name: 'SiteDetail', params: { siteId } })
}

onMounted(() => {
  fetchContainers()
})
</script>
