<script lang="ts" setup>
import { ref, computed } from 'vue'
import { Link, useForm } from '@inertiajs/vue3'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import { formatPrice } from '@/utils/resolvers'
import type { Plan } from '@/types'

interface AvailablePlan extends Plan {
  price_difference: number
  is_upgrade: boolean
}

interface ServiceData {
  id: number
  hostname: string | null
  ipv4_address: string | null
  domain: string | null
  status: string
  service_type: string
  plan: Plan
}

interface Props {
  service: ServiceData
  currentPlan: Plan
  availablePlans: AvailablePlan[]
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

const showConfirmDialog = ref<boolean>(false)
const selectedPlan = ref<AvailablePlan | null>(null)

const form = useForm({
  plan_id: 0,
})

const upgradePlans = computed<AvailablePlan[]>(() =>
  props.availablePlans.filter(plan => plan.is_upgrade),
)

const downgradePlans = computed<AvailablePlan[]>(() =>
  props.availablePlans.filter(plan => !plan.is_upgrade),
)

const serviceLabel = computed<string>(() =>
  props.service.hostname || props.service.domain || `Service #${props.service.id}`,
)

const confirmActionLabel = computed<string>(() => {
  if (!selectedPlan.value) return ''
  return selectedPlan.value.is_upgrade ? 'Upgrade' : 'Downgrade'
})

const confirmActionColor = computed<string>(() => {
  if (!selectedPlan.value) return 'primary'
  return selectedPlan.value.is_upgrade ? 'success' : 'warning'
})

function formatPriceDifference(difference: number): string {
  const abs = Math.abs(difference).toFixed(2)
  if (difference > 0) return `+$${abs}`
  if (difference < 0) return `-$${abs}`
  return '$0.00'
}

function openConfirmDialog(plan: AvailablePlan): void {
  selectedPlan.value = plan
  form.plan_id = plan.id
  showConfirmDialog.value = true
}

function submitUpgrade(): void {
  form.post(`/services/${props.service.id}/upgrade`, {
    onSuccess: () => {
      showConfirmDialog.value = false
      selectedPlan.value = null
    },
  })
}
</script>

<template>
  <div>
    <div class="mb-4">
      <Link
        :href="`/services/${service.id}`"
        class="text-primary text-body-2 text-decoration-none"
      >
        &larr; Back to Service
      </Link>
    </div>

    <!-- Page Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Upgrade / Downgrade
        </div>
        <div class="text-body-2 text-medium-emphasis mt-1">
          {{ serviceLabel }} &mdash; Currently on <strong>{{ currentPlan.name }}</strong>
        </div>
      </div>
    </div>

    <!-- Current Plan -->
    <VCard class="mb-6">
      <VCardTitle class="d-flex align-center ga-2">
        <VIcon
          icon="tabler-star"
          color="primary"
          size="20"
        />
        Current Plan
      </VCardTitle>
      <VCardText>
        <VRow>
          <VCol
            cols="12"
            sm="4"
          >
            <div class="text-body-2 text-medium-emphasis">
              Plan
            </div>
            <div class="text-h6 font-weight-bold mt-1">
              {{ currentPlan.name }}
            </div>
          </VCol>
          <VCol
            cols="12"
            sm="4"
          >
            <div class="text-body-2 text-medium-emphasis">
              Price
            </div>
            <div class="text-h6 font-weight-bold mt-1">
              {{ formatPrice(currentPlan.price, currentPlan.billing_cycle) }}
            </div>
          </VCol>
          <VCol
            cols="12"
            sm="4"
          >
            <div class="text-body-2 text-medium-emphasis">
              Service Type
            </div>
            <div class="text-body-1 text-capitalize mt-1">
              {{ currentPlan.service_type }}
            </div>
          </VCol>
        </VRow>

        <div
          v-if="currentPlan.features && Object.keys(currentPlan.features).length > 0"
          class="mt-4"
        >
          <div class="text-body-2 text-medium-emphasis mb-2">
            Features
          </div>
          <VList density="compact">
            <VListItem
              v-for="(value, key) in currentPlan.features"
              :key="String(key)"
            >
              <template #prepend>
                <VIcon
                  icon="tabler-check"
                  color="success"
                  size="18"
                />
              </template>
              <VListItemTitle class="text-body-2">
                <span class="font-weight-medium text-capitalize">{{ String(key).replace(/_/g, ' ') }}:</span>
                {{ value }}
              </VListItemTitle>
            </VListItem>
          </VList>
        </div>
      </VCardText>
    </VCard>

    <!-- No Plans Available -->
    <VCard v-if="availablePlans.length === 0">
      <VCardText class="text-center py-12">
        <VIcon
          icon="tabler-arrows-exchange"
          size="48"
          class="text-medium-emphasis mb-4"
        />
        <div class="text-h6 text-medium-emphasis mb-2">
          No alternative plans available
        </div>
        <div class="text-body-2 text-medium-emphasis">
          There are no other plans available for this service type.
        </div>
      </VCardText>
    </VCard>

    <!-- Upgrade Plans -->
    <div v-if="upgradePlans.length > 0">
      <div class="text-h5 font-weight-bold mb-4 d-flex align-center ga-2">
        <VIcon
          icon="tabler-arrow-up"
          color="success"
          size="24"
        />
        Upgrade Options
      </div>
      <VRow class="mb-6">
        <VCol
          v-for="plan in upgradePlans"
          :key="plan.id"
          cols="12"
          sm="6"
          lg="4"
        >
          <VCard
            class="h-100"
            border
          >
            <VCardText>
              <div class="d-flex align-center justify-space-between mb-2">
                <div class="text-h6 font-weight-bold">
                  {{ plan.name }}
                </div>
                <VChip
                  color="success"
                  size="small"
                >
                  {{ formatPriceDifference(plan.price_difference) }}/{{ currentPlan.billing_cycle }}
                </VChip>
              </div>

              <div class="text-h5 font-weight-bold mb-4">
                {{ formatPrice(plan.price, plan.billing_cycle) }}
              </div>

              <div
                v-if="plan.description"
                class="text-body-2 text-medium-emphasis mb-4"
              >
                {{ plan.description }}
              </div>

              <!-- Feature Comparison -->
              <div
                v-if="plan.features && Object.keys(plan.features).length > 0"
                class="mb-4"
              >
                <VList density="compact">
                  <VListItem
                    v-for="(value, key) in plan.features"
                    :key="String(key)"
                  >
                    <template #prepend>
                      <VIcon
                        icon="tabler-check"
                        color="success"
                        size="16"
                      />
                    </template>
                    <VListItemTitle class="text-body-2">
                      <span class="font-weight-medium text-capitalize">{{ String(key).replace(/_/g, ' ') }}:</span>
                      {{ value }}
                      <template v-if="currentPlan.features && currentPlan.features[String(key)] && currentPlan.features[String(key)] !== value">
                        <span class="text-medium-emphasis text-caption ml-1">(currently: {{ currentPlan.features[String(key)] }})</span>
                      </template>
                    </VListItemTitle>
                  </VListItem>
                </VList>
              </div>

              <VBtn
                color="success"
                block
                @click="openConfirmDialog(plan)"
              >
                <VIcon
                  icon="tabler-arrow-up"
                  start
                />
                Upgrade
              </VBtn>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </div>

    <!-- Downgrade Plans -->
    <div v-if="downgradePlans.length > 0">
      <div class="text-h5 font-weight-bold mb-4 d-flex align-center ga-2">
        <VIcon
          icon="tabler-arrow-down"
          color="warning"
          size="24"
        />
        Downgrade Options
      </div>
      <VRow class="mb-6">
        <VCol
          v-for="plan in downgradePlans"
          :key="plan.id"
          cols="12"
          sm="6"
          lg="4"
        >
          <VCard
            class="h-100"
            border
          >
            <VCardText>
              <div class="d-flex align-center justify-space-between mb-2">
                <div class="text-h6 font-weight-bold">
                  {{ plan.name }}
                </div>
                <VChip
                  color="warning"
                  size="small"
                >
                  {{ formatPriceDifference(plan.price_difference) }}/{{ currentPlan.billing_cycle }}
                </VChip>
              </div>

              <div class="text-h5 font-weight-bold mb-4">
                {{ formatPrice(plan.price, plan.billing_cycle) }}
              </div>

              <div
                v-if="plan.description"
                class="text-body-2 text-medium-emphasis mb-4"
              >
                {{ plan.description }}
              </div>

              <!-- Feature Comparison -->
              <div
                v-if="plan.features && Object.keys(plan.features).length > 0"
                class="mb-4"
              >
                <VList density="compact">
                  <VListItem
                    v-for="(value, key) in plan.features"
                    :key="String(key)"
                  >
                    <template #prepend>
                      <VIcon
                        icon="tabler-check"
                        :color="currentPlan.features && currentPlan.features[String(key)] && currentPlan.features[String(key)] !== value ? 'warning' : 'success'"
                        size="16"
                      />
                    </template>
                    <VListItemTitle class="text-body-2">
                      <span class="font-weight-medium text-capitalize">{{ String(key).replace(/_/g, ' ') }}:</span>
                      {{ value }}
                      <template v-if="currentPlan.features && currentPlan.features[String(key)] && currentPlan.features[String(key)] !== value">
                        <span class="text-medium-emphasis text-caption ml-1">(currently: {{ currentPlan.features[String(key)] }})</span>
                      </template>
                    </VListItemTitle>
                  </VListItem>
                </VList>
              </div>

              <VBtn
                color="warning"
                block
                @click="openConfirmDialog(plan)"
              >
                <VIcon
                  icon="tabler-arrow-down"
                  start
                />
                Downgrade
              </VBtn>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </div>

    <!-- Confirmation Dialog -->
    <VDialog
      v-model="showConfirmDialog"
      max-width="520"
    >
      <VCard v-if="selectedPlan">
        <VCardTitle class="text-h5 pa-6 pb-2">
          Confirm {{ confirmActionLabel }}
        </VCardTitle>
        <VCardText class="pa-6 pt-2">
          <p class="text-body-1 mb-4">
            Are you sure you want to {{ confirmActionLabel.toLowerCase() }} your service from
            <strong>{{ currentPlan.name }}</strong> to <strong>{{ selectedPlan.name }}</strong>?
          </p>

          <VCard
            variant="tonal"
            :color="confirmActionColor"
            class="mb-4"
          >
            <VCardText>
              <div class="d-flex justify-space-between align-center">
                <div>
                  <div class="text-body-2 text-medium-emphasis">
                    Price Change
                  </div>
                  <div class="text-h6 font-weight-bold">
                    {{ formatPriceDifference(selectedPlan.price_difference) }}/{{ currentPlan.billing_cycle }}
                  </div>
                </div>
                <div class="text-end">
                  <div class="text-body-2 text-medium-emphasis">
                    New Price
                  </div>
                  <div class="text-h6 font-weight-bold">
                    {{ formatPrice(selectedPlan.price, selectedPlan.billing_cycle) }}
                  </div>
                </div>
              </div>
            </VCardText>
          </VCard>

          <VAlert
            v-if="selectedPlan.is_upgrade"
            type="info"
            variant="tonal"
            density="compact"
            class="mb-0"
          >
            An invoice for the price difference will be generated.
          </VAlert>
          <VAlert
            v-else
            type="info"
            variant="tonal"
            density="compact"
            class="mb-0"
          >
            A credit memo for the price difference will be applied to your account.
          </VAlert>
        </VCardText>
        <VCardActions class="pa-6 pt-0">
          <VSpacer />
          <VBtn
            variant="tonal"
            :disabled="form.processing"
            @click="showConfirmDialog = false"
          >
            Cancel
          </VBtn>
          <VBtn
            :color="confirmActionColor"
            :loading="form.processing"
            @click="submitUpgrade"
          >
            <VIcon
              :icon="selectedPlan.is_upgrade ? 'tabler-arrow-up' : 'tabler-arrow-down'"
              start
            />
            Confirm {{ confirmActionLabel }}
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
