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

interface Props {
  subscription: Subscription
  availablePlans: Plan[]
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

const showCancelDialog = ref<boolean>(false)
const cancelImmediately = ref<boolean>(false)
const cancelReason = ref<string>('')
const cancelFeedback = ref<string>('')
const wouldReturn = ref<string | null>(null)

const cancelReasons = [
  'Too expensive',
  'No longer needed',
  'Switching to competitor',
  'Poor performance',
  'Missing features',
  'Technical issues',
  'Other',
]

const cancelForm = useForm({
  immediately: false,
  reason: '',
  feedback: '',
  would_return: null as string | null,
})

const resumeForm = useForm({})

const swapForm = useForm({
  plan_id: '',
})

function openCancelDialog(): void {
  showCancelDialog.value = true
}

function confirmCancel(): void {
  cancelForm.immediately = cancelImmediately.value
  cancelForm.reason = cancelReason.value
  cancelForm.feedback = cancelFeedback.value
  cancelForm.would_return = wouldReturn.value
  cancelForm.post(`/subscriptions/${props.subscription.id}/cancel`, {
    onSuccess: () => {
      showCancelDialog.value = false
    },
  })
}

function resumeSubscription(): void {
  if (resumeForm.processing) return
  resumeForm.post(`/subscriptions/${props.subscription.id}/resume`)
}

function swapPlan(): void {
  swapForm.post(`/subscriptions/${props.subscription.id}/swap`)
}

function formatDate(dateString: string): string {
  return new Date(dateString).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

const currentPlan = computed(() => {
  if (!props.subscription.plan_name) return null
  return {
    name: props.subscription.plan_name,
    price: props.subscription.plan_price,
    billing_cycle: props.subscription.plan_billing_cycle,
    features: props.subscription.plan_features,
  }
})

const isActive = computed<boolean>(() => props.subscription.stripe_status === 'active')
const isCancelling = computed<boolean>(() => !!props.subscription.ends_at && props.subscription.stripe_status !== 'canceled')
const isCanceled = computed<boolean>(() => props.subscription.stripe_status === 'canceled')
</script>

<template>
  <div>
    <!-- Breadcrumb -->
    <div class="d-flex align-center ga-2 mb-4">
      <Link href="/subscriptions" class="text-decoration-none">
        <VBtn variant="text" size="small" color="primary">
          <VIcon icon="tabler-arrow-left" start />
          Subscriptions
        </VBtn>
      </Link>
      <VIcon icon="tabler-chevron-right" size="16" color="disabled" />
      <span class="text-body-2 text-medium-emphasis">{{ currentPlan?.name || subscription.type }}</span>
    </div>

    <div class="d-flex align-center justify-space-between mb-6">
      <div class="text-h4 font-weight-bold">Subscription Details</div>
      <VChip
        :color="resolveSubscriptionStatusColor(subscription.stripe_status)"
        size="small"
        class="text-capitalize"
      >
        {{ subscription.stripe_status }}
      </VChip>
    </div>

    <VRow>
      <!-- Subscription Info -->
      <VCol cols="12" lg="8">
        <VCard class="mb-6">
          <VCardTitle>
            {{ currentPlan?.name || subscription.type }}
          </VCardTitle>
          <VCardText>
            <VRow>
              <VCol cols="6" sm="4">
                <div class="text-body-2 text-medium-emphasis">Gateway</div>
                <div class="text-body-1 text-capitalize mt-1">{{ subscription.gateway || 'stripe' }}</div>
              </VCol>
              <VCol v-if="currentPlan" cols="6" sm="4">
                <div class="text-body-2 text-medium-emphasis">Price</div>
                <div class="text-body-1 font-weight-medium mt-1">{{ formatPrice(currentPlan.price, currentPlan.billing_cycle) }}</div>
              </VCol>
              <VCol v-if="currentPlan" cols="6" sm="4">
                <div class="text-body-2 text-medium-emphasis">Billing Cycle</div>
                <div class="text-body-1 text-capitalize mt-1">{{ currentPlan.billing_cycle }}</div>
              </VCol>
              <VCol v-if="subscription.current_period_start" cols="6" sm="4">
                <div class="text-body-2 text-medium-emphasis">Period Start</div>
                <div class="text-body-1 mt-1">{{ formatDate(subscription.current_period_start) }}</div>
              </VCol>
              <VCol v-if="subscription.current_period_end" cols="6" sm="4">
                <div class="text-body-2 text-medium-emphasis">Period End</div>
                <div class="text-body-1 mt-1">{{ formatDate(subscription.current_period_end) }}</div>
              </VCol>
              <VCol cols="6" sm="4">
                <div class="text-body-2 text-medium-emphasis">Created</div>
                <div class="text-body-1 mt-1">{{ formatDate(subscription.created_at) }}</div>
              </VCol>
            </VRow>

            <!-- Cancellation Notice -->
            <VAlert
              v-if="isCancelling"
              type="warning"
              variant="tonal"
              class="mt-4"
            >
              <div class="font-weight-medium">Subscription cancelling</div>
              <div class="text-body-2">
                Your subscription will end on {{ formatDate(subscription.ends_at!) }}.
                You can resume it before then to keep your service.
              </div>
            </VAlert>

            <VAlert
              v-if="isCanceled"
              type="error"
              variant="tonal"
              class="mt-4"
            >
              <div class="font-weight-medium">Subscription cancelled</div>
              <div class="text-body-2">
                This subscription has been cancelled and is no longer active.
              </div>
            </VAlert>
          </VCardText>
        </VCard>

        <!-- Plan Features -->
        <VCard v-if="currentPlan?.features" class="mb-6">
          <VCardTitle>Plan Features</VCardTitle>
          <VCardText>
            <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="text-capitalize">{{ String(key).replace(/_/g, ' ') }}</span>:
                  <span class="font-weight-medium">{{ value }}</span>
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Change Plan -->
        <VCard v-if="availablePlans.length > 0 && isActive && !isCancelling">
          <VCardTitle>Change Plan</VCardTitle>
          <VCardText>
            <p class="text-body-2 text-medium-emphasis mb-4">
              Switch to a different plan. Your billing will be adjusted automatically.
            </p>
            <VForm @submit.prevent="swapPlan">
              <VRadioGroup v-model="swapForm.plan_id" class="mb-4">
                <VRadio
                  v-for="plan in availablePlans"
                  :key="plan.id"
                  :value="String(plan.id)"
                >
                  <template #label>
                    <div class="d-flex justify-space-between align-center w-100">
                      <span>{{ plan.name }}</span>
                      <div class="d-flex align-center ga-2">
                        <span class="text-medium-emphasis">{{ formatPrice(plan.price, plan.billing_cycle) }}</span>
                        <VChip
                          v-if="currentPlan && parseFloat(plan.price) > parseFloat(currentPlan.price)"
                          color="info"
                          size="x-small"
                          variant="tonal"
                        >
                          Upgrade
                        </VChip>
                        <VChip
                          v-else-if="currentPlan"
                          color="warning"
                          size="x-small"
                          variant="tonal"
                        >
                          Downgrade
                        </VChip>
                      </div>
                    </div>
                  </template>
                </VRadio>
              </VRadioGroup>

              <VBtn
                type="submit"
                color="primary"
                :loading="swapForm.processing"
                :disabled="!swapForm.plan_id || swapForm.processing"
                prepend-icon="tabler-switch-horizontal"
              >
                Change Plan
              </VBtn>
            </VForm>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Actions Sidebar -->
      <VCol cols="12" lg="4">
        <!-- Cancel -->
        <VCard v-if="isActive && !isCancelling" class="mb-6">
          <VCardTitle>Cancel Subscription</VCardTitle>
          <VCardText>
            <p class="text-body-2 text-medium-emphasis mb-4">
              If you cancel, your service will remain active until the end of your current billing period.
            </p>
            <VBtn
              color="error"
              variant="tonal"
              block
              prepend-icon="tabler-x"
              @click="openCancelDialog"
            >
              Cancel Subscription
            </VBtn>
          </VCardText>
        </VCard>

        <!-- Resume -->
        <VCard v-if="isCancelling" class="mb-6">
          <VCardTitle>Resume Subscription</VCardTitle>
          <VCardText>
            <p class="text-body-2 text-medium-emphasis mb-3">
              Your subscription is set to cancel on {{ formatDate(subscription.ends_at!) }}.
              Resume to keep your service running.
            </p>
            <VBtn
              color="success"
              block
              prepend-icon="tabler-player-play"
              :loading="resumeForm.processing"
              :disabled="resumeForm.processing"
              @click="resumeSubscription"
            >
              Resume Subscription
            </VBtn>
          </VCardText>
        </VCard>

        <!-- Quick Info -->
        <VCard>
          <VCardTitle>Quick Info</VCardTitle>
          <VCardText>
            <div class="d-flex flex-column ga-3">
              <div class="d-flex justify-space-between align-center">
                <span class="text-body-2 text-medium-emphasis">Status</span>
                <VChip
                  :color="resolveSubscriptionStatusColor(subscription.stripe_status)"
                  size="small"
                  class="text-capitalize"
                >
                  {{ subscription.stripe_status }}
                </VChip>
              </div>
              <VDivider />
              <div v-if="currentPlan" class="d-flex justify-space-between">
                <span class="text-body-2 text-medium-emphasis">Plan</span>
                <span class="text-body-2 font-weight-medium">{{ currentPlan.name }}</span>
              </div>
              <VDivider />
              <div v-if="currentPlan" class="d-flex justify-space-between">
                <span class="text-body-2 text-medium-emphasis">Price</span>
                <span class="text-body-2 font-weight-medium">{{ formatPrice(currentPlan.price, currentPlan.billing_cycle) }}</span>
              </div>
              <VDivider />
              <div v-if="subscription.current_period_end" class="d-flex justify-space-between">
                <span class="text-body-2 text-medium-emphasis">Next Renewal</span>
                <span class="text-body-2">{{ formatDate(subscription.current_period_end) }}</span>
              </div>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Cancel Confirmation Dialog -->
    <VDialog v-model="showCancelDialog" max-width="500">
      <VCard>
        <VCardTitle class="d-flex align-center ga-2">
          <VIcon icon="tabler-alert-triangle" color="error" />
          Cancel Subscription
        </VCardTitle>
        <VCardText>
          <p class="text-body-1 mb-4">
            Are you sure you want to cancel your subscription?
          </p>

          <VAlert type="info" variant="tonal" class="mb-4">
            <div class="text-body-2">
              By default, your service will remain active until the end of your current billing period.
            </div>
          </VAlert>

          <VSelect
            v-model="cancelReason"
            :items="cancelReasons"
            label="Reason for cancelling (optional)"
            placeholder="Select a reason"
            class="mb-4"
          />

          <VTextarea
            v-model="cancelFeedback"
            label="Any additional feedback? (optional)"
            placeholder="Tell us how we could improve..."
            rows="3"
            class="mb-4"
          />

          <div class="text-body-2 text-medium-emphasis mb-2">Would you consider returning?</div>
          <VRadioGroup
            v-model="wouldReturn"
            inline
            class="mb-4"
          >
            <VRadio label="Yes" value="yes" />
            <VRadio label="Maybe" value="maybe" />
            <VRadio label="No" value="no" />
          </VRadioGroup>

          <VCheckbox
            v-model="cancelImmediately"
            hide-details
            class="mb-2"
          >
            <template #label>
              <div>
                <div class="text-body-2 font-weight-medium">Cancel immediately</div>
                <div class="text-caption text-medium-emphasis">
                  Your service will be terminated right away with no refund.
                </div>
              </div>
            </template>
          </VCheckbox>
        </VCardText>
        <VCardActions class="pa-4 pt-0">
          <VSpacer />
          <VBtn
            variant="outlined"
            @click="showCancelDialog = false"
          >
            Keep Subscription
          </VBtn>
          <VBtn
            color="error"
            :loading="cancelForm.processing"
            @click="confirmCancel"
          >
            Confirm Cancellation
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
