<template>
  <Dialog
    v-model="show"
    :options="{
      title: createdContainer ? 'Creating Container' : 'Create New Container',
      size: 'lg',
    }"
  >
    <template #body-content>
      <!-- Creation Form -->
      <div v-if="!createdContainer" class="space-y-4">
        <FormControl
          label="Container Name"
          v-model="form.name"
          placeholder="my-container"
          description="3-63 chars, starts with letter, lowercase letters/numbers/hyphens only"
          :disabled="creating"
        />

        <FormControl
          label="Image"
          type="select"
          v-model="form.image"
          :options="imageOptions"
          :disabled="creating"
        />

        <!-- Trial mode -->
        <div class="flex items-center justify-between rounded-lg border border-surface-gray-3 px-4 py-3">
          <div>
            <p class="text-sm font-medium text-ink-gray-9">Trial mode</p>
            <p class="text-xs text-ink-gray-5">Demo — fixed 1 user, limited period</p>
          </div>
          <input
            type="checkbox"
            v-model="form.trial"
            :disabled="creating"
            class="h-4 w-4 rounded border-gray-300 text-blue-600 cursor-pointer"
            @change="form.trial && (userCount = [1])"
          />
        </div>

        <!-- User count slider -->
        <div>
          <div class="flex items-center justify-between mb-2">
            <label class="text-sm font-medium text-ink-gray-7">Number of Users</label>
            <Badge class="!rounded-sm" :theme="form.trial ? 'gray' : 'blue'">
              {{ form.trial ? 1 : userCount[0] }} {{ form.trial ? 'user (Trial)' : userCount[0] === 1 ? 'user' : 'users' }}
            </Badge>
          </div>
          <Slider
            v-model="userCount"
            :min="1"
            :max="100"
            :disabled="creating || form.trial"
            class="w-full"
            :class="{ 'opacity-40': form.trial }"
          />
          <div class="flex justify-between mt-1 text-xs text-ink-gray-4">
            <span>1</span>
            <span>50</span>
            <span>100</span>
          </div>
        </div>

        <div v-if="error" class="rounded-lg bg-red-50 p-3 text-sm text-red-600">
          {{ error }}
        </div>
      </div>

      <!-- Progress View -->
      <div v-else class="space-y-4">
        <div class="flex items-center gap-3 p-4 rounded-lg bg-surface-gray-1">
          <div
            class="flex h-12 w-12 items-center justify-center rounded-full"
            :class="statusBgClass"
          >
            <LoadingIndicator v-if="isWaiting" class="h-6 w-6" :class="statusIconClass" />
            <FeatherIcon v-else :name="statusIcon" class="h-6 w-6" :class="statusIconClass" />
          </div>
          <div class="flex-1">
            <p class="font-medium text-ink-gray-9">{{ createdContainer.container_name }}</p>
            <p class="text-sm" :class="statusTextClass">{{ statusMessage }}</p>
          </div>
        </div>

        <!-- Progress Bar -->
        <div v-if="isWaiting" class="space-y-2">
          <div class="h-2 bg-surface-gray-2 rounded-full overflow-hidden">
            <div
              class="h-full bg-blue-500 rounded-full transition-all duration-500"
              :style="{ width: progressWidth }"
            />
          </div>
          <p class="text-xs text-ink-gray-5 text-center">{{ progressText }}</p>
        </div>

        <!-- Error Message -->
        <div v-if="createdContainer.status === 'Error'" class="rounded-lg bg-red-50 p-3 text-sm text-red-600">
          {{ createdContainer.error_message || 'Container creation failed' }}
        </div>
      </div>
    </template>

    <template #actions>
      <div class="flex justify-end gap-2">
        <!-- Form Actions -->
        <template v-if="!createdContainer">
          <Button variant="subtle" @click="closeModal" :disabled="creating">Cancel</Button>
          <Button variant="solid" @click="createContainer" :loading="creating">
            Create Container
          </Button>
        </template>

        <!-- Progress Actions -->
        <template v-else>
          <Button
            v-if="isWaiting"
            variant="subtle"
            @click="closeModal"
          >
            Run in Background
          </Button>
          <Button
            v-else
            variant="solid"
            @click="finishAndClose"
          >
            {{ createdContainer.status === 'Error' ? 'Close' : 'Done' }}
          </Button>
        </template>
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import { reactive, computed, ref, watch, onUnmounted } from 'vue'
import { Dialog, Button, FormControl, LoadingIndicator, FeatherIcon, createResource, Slider, Badge } from 'frappe-ui'
import { getStatusStyles } from '@/utils/statusStyles'

const POLL_INTERVAL = 2000 // 2 seconds

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue', 'created'])

const show = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const creating = ref(false)
const error = ref('')
const createdContainer = ref(null)
const progress = ref(0)
let pollInterval = null
let progressInterval = null

const form = reactive({
  name: '',
  image: 'alpine/edge',
  trial: false,
})
const userCount = ref([10])

const imageOptions = [
  { label: 'Alpine Edge', value: 'alpine/edge' },
  { label: 'Ubuntu 22.04', value: 'ubuntu/22.04' },
  { label: 'Ubuntu 24.04', value: 'ubuntu/24.04' },
  { label: 'Debian 12', value: 'debian/12' },
]

// Status helpers
const isWaiting = computed(() =>
  createdContainer.value &&
  ['Creating', 'Pending'].includes(createdContainer.value.status)
)

const statusStyles = computed(() =>
  getStatusStyles(createdContainer.value?.status)
)
const statusBgClass = computed(() => statusStyles.value.bgClass)
const statusIconClass = computed(() => statusStyles.value.iconClass)
const statusTextClass = computed(() => statusStyles.value.textClass)
const statusIcon = computed(() => statusStyles.value.icon)

const statusMessage = computed(() => {
  if (!createdContainer.value) return ''
  switch (createdContainer.value.status) {
    case 'Pending': return 'Queued for creation...'
    case 'Creating': return 'Creating container...'
    case 'Running': return 'Container is ready!'
    case 'Error': return 'Creation failed'
    default: return createdContainer.value.status
  }
})

const progressWidth = computed(() => `${Math.min(progress.value, 95)}%`)
const progressText = computed(() => {
  if (progress.value < 30) return 'Initializing...'
  if (progress.value < 60) return 'Setting up container...'
  if (progress.value < 90) return 'Almost ready...'
  return 'Finalizing...'
})

// Resources
const createContainerResource = createResource({
  url: 'cloud_portal.cloud_portal.doctype.cloud_container.cloud_container.create_user_container',
  onSuccess(data) {
    creating.value = false
    if (data.success) {
      createdContainer.value = {
        name: data.name,
        container_name: data.container_name,
        status: 'Creating',
      }
      startPolling(data.name)
      startProgressAnimation()
    } else {
      error.value = data.message || 'Failed to create container'
    }
  },
  onError(err) {
    creating.value = false
    error.value = err.messages?.[0] || err.message || 'Failed to create container'
  }
})

const containerStatusResource = createResource({
  url: 'frappe.client.get_value',
  onSuccess(data) {
    if (data && createdContainer.value) {
      createdContainer.value.status = data.status
      createdContainer.value.error_message = data.error_message

      // Stop polling when done
      if (!['Creating', 'Pending'].includes(data.status)) {
        stopPolling()
        progress.value = 100
      }
    }
  },
})

function createContainer() {
  const name = form.name.trim()

  if (!name || !/^[a-z][a-z0-9-]{2,62}$/.test(name)) {
    error.value = 'Name must be 3-63 chars, start with letter, only lowercase letters, numbers, hyphens'
    return
  }

  error.value = ''
  creating.value = true

  createContainerResource.fetch({
    container_name: name,
    image: form.image,
    container_type: 'container',
    max_users: form.trial ? 1 : userCount.value[0],
    trial: form.trial ? 1 : 0,
  })
}

function startPolling(containerName) {
  pollInterval = setInterval(() => {
    containerStatusResource.fetch({
      doctype: 'Cloud Container',
      filters: JSON.stringify({ name: containerName }),
      fieldname: ['status', 'error_message'],
    })
  }, POLL_INTERVAL)
}

function startProgressAnimation() {
  progress.value = 0
  progressInterval = setInterval(() => {
    if (progress.value < 90) {
      progress.value += Math.random() * 10 + 2
    }
  }, 500)
}

function stopPolling() {
  if (pollInterval) {
    clearInterval(pollInterval)
    pollInterval = null
  }
  if (progressInterval) {
    clearInterval(progressInterval)
    progressInterval = null
  }
}

function resetForm() {
  form.name = ''
  form.image = 'alpine/edge'
  form.trial = false
  userCount.value = [10]
  error.value = ''
  createdContainer.value = null
  progress.value = 0
}

function closeModal() {
  stopPolling()
  show.value = false
  // Emit created if container was started
  if (createdContainer.value) {
    emit('created')
  }
  // Reset after animation
  setTimeout(resetForm, 300)
}

function finishAndClose() {
  emit('created')
  show.value = false
  setTimeout(resetForm, 300)
}

// Cleanup on unmount
onUnmounted(() => {
  stopPolling()
})

// Reset when modal closes externally
watch(show, (newVal) => {
  if (!newVal) {
    stopPolling()
    setTimeout(resetForm, 300)
  }
})
</script>
