<template>
  <div class="flex flex-col h-full">
    <LayoutHeader :title="$t('sites.title')">
      <template #right>
        <Button variant="subtle" @click="refreshData" :loading="containers.loading">
          <template #prefix>
            <FeatherIcon name="refresh-cw" class="h-4 w-4" />
          </template>
          {{ $t('common.refresh') }}
        </Button>
        <Button variant="solid" @click="openCreateModal">
          <template #prefix>
            <FeatherIcon name="plus" class="h-4 w-4" />
          </template>
          {{ $t('sites.newSite') }}
        </Button>
      </template>
    </LayoutHeader>

    <div class="flex-1 overflow-auto p-5">
      <!-- Filters row -->
      <div class="mb-4 flex items-center gap-3 flex-wrap">
        <!-- Server selector -->
        <div class="flex items-center gap-2">
          <FeatherIcon name="cloud" class="h-4 w-4 text-ink-gray-4" />
          <FormControl
            v-model="selectedServer"
            type="select"
            :options="availableServerOptions"
            class="w-40"
          />
        </div>

        <div class="h-6 w-px bg-gray-200"></div>

        <TextInput
          v-model="searchQuery"
          type="text"
          :placeholder="$t('common.search') + '...'"
          class="w-56"
        >
          <template #prefix>
            <FeatherIcon name="search" class="h-4 w-4 text-ink-gray-4" />
          </template>
        </TextInput>
        <div class="flex gap-1">
          <button
            v-for="f in statusFilters"
            :key="f.value"
            class="px-3 py-1 rounded text-sm transition-colors"
            :class="statusFilter === f.value
              ? 'bg-surface-selected shadow-sm text-ink-gray-9 font-medium'
              : 'text-ink-gray-5 hover:bg-surface-gray-2'"
            @click="statusFilter = f.value"
          >
            {{ f.label }}
          </button>
        </div>
      </div>

      <!-- No servers configured -->
      <div v-if="availableServers.data && availableServers.data.length === 0" class="flex flex-col items-center justify-center h-64 gap-3">
        <FeatherIcon name="cloud-off" class="h-10 w-10 text-ink-gray-4" />
        <p class="text-sm text-ink-gray-7 font-medium">No container servers configured</p>
        <p class="text-xs text-ink-gray-5">Add a server with "Container Server" role in the Servers tab</p>
        <Button variant="solid" @click="$router.push({ name: 'Servers' })">
          Go to Servers
        </Button>
      </div>

      <div v-else-if="containers.loading" class="flex items-center justify-center h-64">
        <Spinner class="h-8 w-8" />
      </div>

      <!-- Error state -->
      <div v-else-if="containers.error" class="flex flex-col items-center justify-center h-64 gap-3">
        <FeatherIcon name="alert-circle" class="h-10 w-10 text-red-500" />
        <p class="text-sm text-ink-gray-5">Failed to load containers</p>
        <p class="text-xs text-ink-gray-4">{{ containers.error }}</p>
        <Button variant="subtle" @click="containers.reload()">Retry</Button>
      </div>

      <!-- Sites Cards Grid -->
      <div v-else-if="filteredSites.length" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <div
          v-for="site in filteredSites"
          :key="site.container_name"
          class="rounded-lg border p-4 shadow-sm hover:shadow-md transition-shadow cursor-pointer"
          @click="goToSite(site)"
        >
          <div class="flex items-start justify-between mb-3">
            <div class="flex items-center gap-3">
              <div
                class="flex h-10 w-10 items-center justify-center rounded-lg"
                :class="getStatusBg(site.status)"
              >
                <FeatherIcon
                  :name="getStatusIcon(site.status)"
                  class="h-5 w-5"
                  :class="getStatusColor(site.status)"
                />
              </div>
              <div>
                <p class="font-medium text-ink-gray-9">{{ site.name }}</p>
                <p class="text-sm text-ink-gray-5">{{ site.image || site.type }}</p>
              </div>
            </div>
            <Badge
              :variant="getStatusBadge(site.status)"
              :label="site.status"
            />
          </div>
          <div class="grid grid-cols-2 gap-2 text-sm mb-2">
            <div>
              <p class="text-ink-gray-4 text-xs">IP</p>
              <p class="font-mono text-ink-gray-7">{{ site.ip_address || '-' }}</p>
            </div>
            <div>
              <p class="text-ink-gray-4 text-xs">{{ $t('sites.siteOwner') }}</p>
              <p class="text-ink-gray-7">{{ site.owner || '-' }}</p>
            </div>
          </div>
          <div class="flex items-center justify-between text-xs text-ink-gray-4 pt-2 border-t">
            <span>{{ site.created }}</span>
            <FeatherIcon name="chevron-right" class="h-4 w-4" />
          </div>
        </div>
      </div>

      <EmptyState
        v-else
        icon="server"
        :title="$t('sites.noSites')"
        :description="$t('sites.createFirst')"
      >
        <template #action>
          <Button variant="solid" @click="openCreateModal">
            {{ $t('sites.newSite') }}
          </Button>
        </template>
      </EmptyState>
    </div>

    <!-- Create Site Modal -->
    <Dialog v-model="showCreateModal" :options="{ title: $t('sites.newSite') }">
      <template #body-content>
        <div class="space-y-4">
          <FormControl
            v-model="newSite.name"
            :label="$t('sites.siteName')"
            type="text"
            required
          />

          <!-- Image selection -->
          <div v-if="images.loading" class="flex items-center gap-2 text-sm text-ink-gray-5 py-2">
            <Spinner class="h-4 w-4" /> Loading images...
          </div>
          <div v-else-if="images.error" class="text-sm text-red-500 py-2">
            Failed to load images
            <Button variant="link" size="sm" @click="images.reload()">Retry</Button>
          </div>
          <FormControl
            v-else
            v-model="newSite.image"
            :label="$t('sites.siteImage')"
            type="select"
            :options="imageOptions"
          />

          <FormControl
            v-model="newSite.owner"
            :label="$t('sites.siteOwner')"
            type="text"
          />

          <!-- Target Server -->
          <FormControl
            v-model="newSite.target_server"
            :label="$t('sites.targetServer')"
            type="select"
            :options="serverOptions"
            :description="$t('sites.targetServerDesc')"
          />

          <!-- Full deploy toggle -->
          <div class="flex items-center gap-2 pt-2">
            <input
              id="fullDeploy"
              v-model="newSite.fullDeploy"
              type="checkbox"
              class="h-4 w-4 rounded border-gray-300"
            />
            <label for="fullDeploy" class="text-sm text-ink-gray-7">
              Full deploy with volumes (MySQL + Frontend)
            </label>
          </div>

          <!-- Volume config (shown when fullDeploy is checked) -->
          <div v-if="newSite.fullDeploy" class="space-y-3 border rounded-lg p-3 bg-surface-gray-1">
            <p class="text-xs font-medium text-ink-gray-5 uppercase">Volume Configuration</p>
            <FormControl
              v-model="newSite.pool_name"
              label="Storage Pool"
              type="text"
            />
            <div
              v-for="(vol, idx) in newSite.volumes"
              :key="idx"
              class="flex items-center gap-2 text-sm"
            >
              <span class="text-ink-gray-5 w-20">{{ vol.name }}</span>
              <span class="text-ink-gray-7 font-mono text-xs flex-1">{{ vol.source_path }}</span>
            </div>
          </div>

          <!-- Error display -->
          <div v-if="createError" class="text-sm text-red-500 bg-red-50 p-2 rounded">
            {{ createError }}
          </div>
        </div>
      </template>
      <template #actions>
        <Button variant="subtle" @click="showCreateModal = false">
          {{ $t('common.cancel') }}
        </Button>
        <Button variant="solid" @click="createSite" :loading="creating">
          {{ newSite.fullDeploy ? 'Deploy' : $t('common.create') }}
        </Button>
      </template>
    </Dialog>

    <!-- Deploy Progress/Result Modal -->
    <Dialog v-model="showDeployProgress" :options="{ title: deploying ? 'Deploying...' : 'Deploy Result', size: 'lg' }">
      <template #body-content>
        <div class="space-y-4">
          <!-- Progress indicator during deploy -->
          <div v-if="deploying" class="flex flex-col items-center gap-4 py-6">
            <Spinner class="h-10 w-10 text-blue-500" />
            <div class="text-center">
              <p class="text-sm font-medium text-ink-gray-8">Creating container with volumes...</p>
              <p class="text-xs text-ink-gray-5 mt-1">This may take a few minutes</p>
            </div>
            <div class="w-full bg-surface-gray-2 rounded-full h-2 overflow-hidden">
              <div class="h-full bg-blue-500 rounded-full animate-pulse" style="width: 60%"></div>
            </div>
          </div>

          <!-- Result after deploy completes -->
          <template v-else>
            <div class="flex items-center gap-3">
              <FeatherIcon
                v-if="deployResult.success"
                name="check-circle"
                class="h-6 w-6 text-green-600"
              />
              <FeatherIcon
                v-else
                name="x-circle"
                class="h-6 w-6 text-red-600"
              />
              <span class="text-sm font-medium" :class="deployResult.success ? 'text-green-700' : 'text-red-700'">
                {{ deployResult.message }}
              </span>
            </div>

            <!-- Deploy logs -->
            <div v-if="deployResult.logs?.length" class="mt-4">
              <p class="text-xs font-medium text-ink-gray-5 uppercase mb-2">Deploy Logs</p>
              <div class="bg-surface-gray-1 rounded-lg p-3 max-h-64 overflow-y-auto font-mono text-xs">
                <div
                  v-for="(log, idx) in deployResult.logs"
                  :key="idx"
                  class="py-0.5"
                  :class="{
                    'text-green-600': log.includes('✓'),
                    'text-red-600': log.includes('✗') || log.includes('Error'),
                    'text-ink-gray-6': !log.includes('✓') && !log.includes('✗'),
                    'font-semibold': log.includes('==='),
                  }"
                >
                  {{ log }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </template>
      <template #actions>
        <Button
          v-if="!deploying"
          variant="solid"
          @click="showDeployProgress = false; containers.reload()"
        >
          Close
        </Button>
      </template>
    </Dialog>
  </div>
</template>

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

const router = useRouter()
const searchQuery = ref('')
const statusFilter = ref('all')
const selectedServer = ref('')
const showCreateModal = ref(false)
const creating = ref(false)
const createError = ref('')
const showDeployProgress = ref(false)
const deploying = ref(false)
const deployResult = ref({
  success: false,
  message: '',
  logs: [],
})

// Available servers for filter dropdown - use container servers from Servers API
const availableServers = createResource({
  url: 'admin_panel.api.servers.get_container_servers',
  auto: true,
})

const availableServerOptions = computed(() => {
  const servers = availableServers.data || []
  if (servers.length === 0) {
    return []
  }
  return servers.map(s => ({
    label: `${s.name}${s.status !== 'online' ? ' (offline)' : ''}`,
    value: s.name,
  }))
})

const containers = createResource({
  url: 'admin_panel.api.sites.get_all_containers',
  auto: false,
})

const images = createResource({
  url: 'admin_panel.api.sites.get_images',
  auto: false,
})

// Load containers for a specific server
function loadContainersForServer(serverName) {
  if (!serverName) return
  containers.fetch({ target_server: serverName })
  images.fetch({ target_server: serverName })
}

// Reload when server changes
watch(selectedServer, (newServer) => {
  if (newServer) {
    loadContainersForServer(newServer)
  }
})

// Auto-select first server when available servers are loaded
watch(() => availableServers.data, (servers) => {
  if (servers && servers.length > 0 && !selectedServer.value) {
    selectedServer.value = servers[0].name
    // Load containers for the first server
    loadContainersForServer(servers[0].name)
  }
}, { immediate: true })

const newSite = ref({
  name: '',
  image: '',
  owner: '',
  target_server: '',
  fullDeploy: false,
  pool_name: 'default',
  volumes: [
    { name: 'mysql', source_path: '/var/lib/mysql', device_name: 'mysql' },
    { name: 'frontend', source_path: '/home/frappe/frappe-bench/sites/frontend', device_name: 'frontend' },
  ],
})

const serverOptions = computed(() => {
  const servers = availableServers.data || []
  return servers.map(s => ({
    label: `${s.name}${s.status !== 'online' ? ' (' + s.status + ')' : ''}`,
    value: s.name,
  }))
})

// Reload images when target server changes in create modal
watch(() => newSite.value.target_server, (newServer) => {
  if (newServer) {
    newSite.value.image = ''
    images.fetch({ target_server: newServer })
  }
})

const imageOptions = computed(() => {
  const list = images.data || []
  return list.map(img => ({
    label: img.alias || img.description || img.fingerprint?.slice(0, 12) || 'Unknown',
    value: img.alias || img.fingerprint,
  }))
})

const statusFilters = [
  { value: 'all', label: 'All' },
  { value: 'Running', label: 'Running' },
  { value: 'Stopped', label: 'Stopped' },
  { value: 'Error', label: 'Error' },
]

const sites = computed(() => containers.data || [])

const filteredSites = computed(() => {
  let result = sites.value
  if (statusFilter.value !== 'all') {
    result = result.filter(s => s.status === statusFilter.value)
  }
  if (searchQuery.value) {
    const q = searchQuery.value.toLowerCase()
    result = result.filter(s =>
      s.name.toLowerCase().includes(q) ||
      s.container_name?.toLowerCase().includes(q) ||
      s.owner?.toLowerCase().includes(q)
    )
  }
  return result
})

function getStatusBg(status) {
  return { Running: 'bg-green-100', Stopped: 'bg-orange-100', Error: 'bg-red-100', Creating: 'bg-blue-100' }[status] || 'bg-surface-gray-2'
}
function getStatusIcon(status) {
  return { Running: 'play-circle', Stopped: 'pause-circle', Error: 'alert-circle', Creating: 'loader' }[status] || 'server'
}
function getStatusColor(status) {
  return { Running: 'text-green-600', Stopped: 'text-orange-600', Error: 'text-red-600', Creating: 'text-blue-600' }[status] || 'text-ink-gray-5'
}
function getStatusBadge(status) {
  return { Running: 'success', Stopped: 'warning', Error: 'error', Creating: 'info' }[status] || 'subtle'
}

function refreshData() {
  if (selectedServer.value) {
    loadContainersForServer(selectedServer.value)
  }
}

function goToSite(site) {
  router.push({
    name: 'SiteDetail',
    params: { siteId: site.container_name },
    query: { server: site.server || selectedServer.value || '' }
  })
}

function openCreateModal() {
  createError.value = ''
  // Auto-select current server
  newSite.value.target_server = selectedServer.value || ''
  showCreateModal.value = true
  // Load images for the selected server
  if (newSite.value.target_server) {
    images.fetch({ target_server: newSite.value.target_server })
  }
}

async function createSite() {
  createError.value = ''

  if (!newSite.value.name) {
    createError.value = 'Container name is required'
    return
  }

  if (!newSite.value.image) {
    createError.value = 'Please select an image'
    return
  }

  creating.value = true
  try {
    if (newSite.value.fullDeploy) {
      // Full deploy with volumes (synchronous - may take time)
      showCreateModal.value = false
      deploying.value = true
      deployResult.value = { success: false, message: '', logs: [] }
      showDeployProgress.value = true

      const resp = await call('admin_panel.api.sites.deploy_container_full', {
        container_name: newSite.value.name,
        image: newSite.value.image,
        pool_name: newSite.value.pool_name,
        volumes_config: JSON.stringify(newSite.value.volumes),
        target_server: newSite.value.target_server || null,
      })

      deploying.value = false
      deployResult.value = {
        success: resp.success,
        message: resp.message,
        logs: resp.logs || [],
      }
    } else {
      // Simple create
      await call('admin_panel.api.sites.create_container', {
        container_name: newSite.value.name,
        image: newSite.value.image,
        container_type: 'container',
        target_server: newSite.value.target_server || null,
      })
      showCreateModal.value = false
      containers.reload()
    }
    // Reset form
    newSite.value = {
      name: '',
      image: '',
      owner: '',
      target_server: selectedServer.value || '',
      fullDeploy: false,
      pool_name: 'default',
      volumes: [
        { name: 'mysql', source_path: '/var/lib/mysql', device_name: 'mysql' },
        { name: 'frontend', source_path: '/home/frappe/frappe-bench/sites/frontend', device_name: 'frontend' },
      ],
    }
  } catch (e) {
    console.error('Failed to create container:', e)
    deploying.value = false
    if (showDeployProgress.value) {
      deployResult.value = {
        success: false,
        message: e.message || e.exc || 'Deploy failed',
        logs: [`Error: ${e.message || e.exc}`],
      }
    } else {
      createError.value = e.message || e.exc || 'Failed to create container'
    }
  } finally {
    creating.value = false
  }
}

// Component lifecycle
onMounted(() => {
  // Refresh data on mount
})

onUnmounted(() => {
  // Cleanup
})
</script>
