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

interface Props {
  services: Service[]
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

const viewMode = ref<'grid' | 'list'>('grid')

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '--'
  return new Date(dateStr).toLocaleDateString()
}

const serviceTypeIcon = (type: string): string => {
  const icons: Record<string, string> = {
    vps: 'tabler-server',
    dedicated: 'tabler-server-2',
    'game-server': 'tabler-device-gamepad-2',
    'web-hosting': 'tabler-world-www',
  }
  return icons[type] ?? 'tabler-server'
}

const serviceCounts = computed(() => {
  const counts = {
    total: props.services.length,
    active: props.services.filter(s => s.status === 'active').length,
    suspended: props.services.filter(s => s.status === 'suspended').length,
    pending: props.services.filter(s => s.status === 'pending').length,
  }
  return counts
})
</script>

<template>
  <div>
    <!-- Header -->
    <div class="mb-8">
      <div class="d-flex flex-wrap align-center justify-space-between gap-4 mb-4">
        <div>
          <h1 class="text-h3 font-weight-bold mb-2" style="font-family: 'DM Sans', sans-serif; letter-spacing: -0.02em;">
            Your Services
          </h1>
          <p class="text-body-1 text-medium-emphasis">
            Manage your hosting services and server infrastructure
          </p>
        </div>
        <Link
          href="/plans"
          class="text-decoration-none"
        >
          <VBtn
            size="large"
            color="primary"
            class="text-none font-weight-semibold px-6"
            elevation="0"
          >
            <VIcon
              icon="tabler-plus"
              start
              size="20"
            />
            Order New Service
          </VBtn>
        </Link>
      </div>

      <!-- Stats Overview -->
      <VRow v-if="services.length > 0">
        <VCol
          cols="6"
          md="3"
        >
          <VCard
            class="stat-card"
            :style="{
              borderLeft: '3px solid rgb(var(--v-theme-primary))',
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            }"
            elevation="0"
          >
            <VCardText class="pa-4">
              <div class="d-flex align-center justify-space-between">
                <div>
                  <div class="text-h4 font-weight-bold mb-1">
                    {{ serviceCounts.total }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Total Services
                  </div>
                </div>
                <VAvatar
                  color="primary"
                  variant="tonal"
                  size="48"
                >
                  <VIcon
                    icon="tabler-server-2"
                    size="24"
                  />
                </VAvatar>
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol
          cols="6"
          md="3"
        >
          <VCard
            class="stat-card"
            :style="{
              borderLeft: '3px solid rgb(var(--v-theme-success))',
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            }"
            elevation="0"
          >
            <VCardText class="pa-4">
              <div class="d-flex align-center justify-space-between">
                <div>
                  <div class="text-h4 font-weight-bold mb-1">
                    {{ serviceCounts.active }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Active
                  </div>
                </div>
                <VAvatar
                  color="success"
                  variant="tonal"
                  size="48"
                >
                  <VIcon
                    icon="tabler-circle-check"
                    size="24"
                  />
                </VAvatar>
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol
          cols="6"
          md="3"
        >
          <VCard
            class="stat-card"
            :style="{
              borderLeft: '3px solid rgb(var(--v-theme-warning))',
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            }"
            elevation="0"
          >
            <VCardText class="pa-4">
              <div class="d-flex align-center justify-space-between">
                <div>
                  <div class="text-h4 font-weight-bold mb-1">
                    {{ serviceCounts.pending }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Pending
                  </div>
                </div>
                <VAvatar
                  color="warning"
                  variant="tonal"
                  size="48"
                >
                  <VIcon
                    icon="tabler-clock"
                    size="24"
                  />
                </VAvatar>
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol
          cols="6"
          md="3"
        >
          <VCard
            class="stat-card"
            :style="{
              borderLeft: '3px solid rgb(var(--v-theme-error))',
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
            }"
            elevation="0"
          >
            <VCardText class="pa-4">
              <div class="d-flex align-center justify-space-between">
                <div>
                  <div class="text-h4 font-weight-bold mb-1">
                    {{ serviceCounts.suspended }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    Suspended
                  </div>
                </div>
                <VAvatar
                  color="error"
                  variant="tonal"
                  size="48"
                >
                  <VIcon
                    icon="tabler-alert-circle"
                    size="24"
                  />
                </VAvatar>
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </div>

    <!-- View Mode Toggle -->
    <div
      v-if="services.length > 0"
      class="d-flex justify-end mb-6"
    >
      <VBtnToggle
        v-model="viewMode"
        mandatory
        variant="outlined"
        divided
      >
        <VBtn value="grid">
          <VIcon icon="tabler-layout-grid" />
        </VBtn>
        <VBtn value="list">
          <VIcon icon="tabler-list" />
        </VBtn>
      </VBtnToggle>
    </div>

    <!-- Empty State -->
    <VCard
      v-if="services.length === 0"
      class="empty-state"
      elevation="0"
    >
      <VCardText class="text-center pa-12">
        <div class="empty-icon-wrapper mb-6">
          <VIcon
            icon="tabler-server-off"
            size="64"
            class="text-medium-emphasis"
            style="opacity: 0.5;"
          />
        </div>
        <h3 class="text-h4 font-weight-bold mb-3" style="font-family: 'DM Sans', sans-serif;">
          No Services Yet
        </h3>
        <p class="text-body-1 text-medium-emphasis mb-6" style="max-width: 480px; margin-left: auto; margin-right: auto;">
          Your services will appear here once you've ordered them. Browse our plans to get started with powerful hosting solutions.
        </p>
        <Link
          href="/plans"
          class="text-decoration-none"
        >
          <VBtn
            size="large"
            color="primary"
            class="text-none px-8"
          >
            <VIcon
              icon="tabler-shopping-cart"
              start
            />
            Browse Plans
          </VBtn>
        </Link>
      </VCardText>
    </VCard>

    <!-- Grid View -->
    <VRow v-if="services.length > 0 && viewMode === 'grid'">
      <VCol
        v-for="(service, index) in services"
        :key="service.id"
        cols="12"
        md="6"
        lg="4"
      >
        <VCard
          class="service-card h-100"
          elevation="0"
          :style="{
            animationDelay: `${index * 50}ms`,
          }"
        >
          <!-- Card Header with gradient overlay -->
          <div
            class="service-card-header pa-4"
            :style="{
              background: `linear-gradient(135deg, rgb(var(--v-theme-${resolveServiceTypeColor(service.service_type)})) 0%, rgb(var(--v-theme-${resolveServiceTypeColor(service.service_type)}-darken-1)) 100%)`,
              position: 'relative',
              overflow: 'hidden',
            }"
          >
            <div
              style="position: absolute; top: 0; right: 0; width: 100px; height: 100px; background: rgba(255,255,255,0.1); border-radius: 50%; transform: translate(30%, -30%);"
            />
            <div class="d-flex align-center justify-space-between position-relative">
              <div class="d-flex align-center gap-3">
                <VAvatar
                  :color="resolveServiceTypeColor(service.service_type)"
                  variant="flat"
                  size="48"
                  style="background: rgba(255,255,255,0.2);"
                >
                  <VIcon
                    :icon="serviceTypeIcon(service.service_type)"
                    size="24"
                    color="white"
                  />
                </VAvatar>
                <div>
                  <div class="text-body-2 text-white" style="opacity: 0.9;">
                    {{ service.plan?.name || 'Service' }}
                  </div>
                  <div class="text-caption text-white" style="opacity: 0.7;">
                    {{ service.platform }}
                  </div>
                </div>
              </div>
              <VChip
                :color="resolveServiceStatusColor(service.status)"
                size="small"
                class="text-capitalize status-pulse"
              >
                {{ service.status }}
              </VChip>
            </div>
          </div>

          <!-- Card Body -->
          <VCardText class="pa-4">
            <h3 class="text-h6 font-weight-bold mb-3" style="font-family: 'DM Sans', sans-serif;">
              {{ service.hostname || service.domain || `Service #${service.id}` }}
            </h3>

            <div class="service-details mb-4">
              <div class="d-flex align-center justify-space-between mb-2">
                <span class="text-body-2 text-medium-emphasis">
                  <VIcon
                    icon="tabler-network"
                    size="16"
                    class="me-1"
                  />
                  IP Address
                </span>
                <span class="text-body-2 font-weight-medium">
                  <code v-if="service.ipv4_address">{{ service.ipv4_address }}</code>
                  <span
                    v-else
                    class="text-medium-emphasis"
                  >Pending</span>
                </span>
              </div>

              <div class="d-flex align-center justify-space-between mb-2">
                <span class="text-body-2 text-medium-emphasis">
                  <VIcon
                    icon="tabler-coin"
                    size="16"
                    class="me-1"
                  />
                  Price
                </span>
                <span class="text-body-2 font-weight-medium">
                  {{ service.plan ? formatPrice(service.plan.price, service.plan.billing_cycle) : '--' }}
                </span>
              </div>

              <div class="d-flex align-center justify-space-between">
                <span class="text-body-2 text-medium-emphasis">
                  <VIcon
                    icon="tabler-calendar"
                    size="16"
                    class="me-1"
                  />
                  Next Renewal
                </span>
                <span class="text-body-2 font-weight-medium">
                  {{ service.subscription?.current_period_end ? formatDate(service.subscription.current_period_end) : '--' }}
                </span>
              </div>
            </div>

            <VDivider class="my-4" />

            <Link
              :href="`/services/${service.id}`"
              class="text-decoration-none"
            >
              <VBtn
                block
                color="primary"
                variant="flat"
                class="text-none"
              >
                <VIcon
                  icon="tabler-settings"
                  start
                  size="20"
                />
                Manage Service
                <VIcon
                  icon="tabler-arrow-right"
                  end
                  size="18"
                />
              </VBtn>
            </Link>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- List View -->
    <VCard
      v-if="services.length > 0 && viewMode === 'list'"
      elevation="0"
    >
      <VTable hover>
        <thead>
          <tr>
            <th class="font-weight-bold">
              Service
            </th>
            <th class="font-weight-bold">
              Plan
            </th>
            <th class="font-weight-bold">
              Type
            </th>
            <th class="font-weight-bold">
              Status
            </th>
            <th class="font-weight-bold">
              IP Address
            </th>
            <th class="font-weight-bold">
              Renewal Date
            </th>
            <th class="text-end font-weight-bold">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="service in services"
            :key="service.id"
            class="service-row"
          >
            <td>
              <div class="d-flex align-center gap-3">
                <VAvatar
                  :color="resolveServiceTypeColor(service.service_type)"
                  variant="tonal"
                  size="36"
                >
                  <VIcon
                    :icon="serviceTypeIcon(service.service_type)"
                    size="20"
                  />
                </VAvatar>
                <div>
                  <div class="font-weight-medium">
                    {{ service.hostname || service.domain || `Service #${service.id}` }}
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    {{ service.platform }}
                  </div>
                </div>
              </div>
            </td>
            <td>
              <div class="font-weight-medium">
                {{ service.plan?.name || '--' }}
              </div>
              <div
                v-if="service.plan"
                class="text-body-2 text-medium-emphasis"
              >
                {{ formatPrice(service.plan.price, service.plan.billing_cycle) }}
              </div>
            </td>
            <td>
              <VChip
                :color="resolveServiceTypeColor(service.service_type)"
                size="small"
                class="text-capitalize"
              >
                {{ service.service_type }}
              </VChip>
            </td>
            <td>
              <VChip
                :color="resolveServiceStatusColor(service.status)"
                size="small"
                class="text-capitalize status-pulse"
              >
                {{ service.status }}
              </VChip>
            </td>
            <td>
              <code v-if="service.ipv4_address">{{ service.ipv4_address }}</code>
              <span
                v-else
                class="text-medium-emphasis"
              >--</span>
            </td>
            <td>
              {{ service.subscription?.current_period_end ? formatDate(service.subscription.current_period_end) : '--' }}
            </td>
            <td class="text-end">
              <Link
                :href="`/services/${service.id}`"
                class="text-decoration-none"
              >
                <VBtn
                  variant="tonal"
                  size="small"
                  color="primary"
                  class="text-none"
                >
                  <VIcon
                    icon="tabler-settings"
                    start
                    size="18"
                  />
                  Manage
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>
    </VCard>
  </div>
</template>

<style scoped>
/* Typography */
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap');

/* Stats Cards */
.stat-card {
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, transparent 0%, rgba(var(--v-theme-primary), 0.03) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(var(--v-theme-primary), 0.12);
}

/* Service Cards */
.service-card {
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: fadeInUp 0.5s ease-out backwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.service-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
  border-color: rgba(var(--v-theme-primary), 0.3);
}

.service-card-header {
  transition: all 0.3s ease;
}

.service-card:hover .service-card-header {
  filter: brightness(1.05);
}

/* Status Pulse Animation */
.status-pulse {
  position: relative;
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.85;
  }
}

/* Empty State */
.empty-state {
  border: 2px dashed rgba(var(--v-border-color), var(--v-border-opacity));
  background: linear-gradient(135deg, rgba(var(--v-theme-surface), 1) 0%, rgba(var(--v-theme-primary), 0.02) 100%);
}

.empty-icon-wrapper {
  position: relative;
  display: inline-block;
}

.empty-icon-wrapper::before {
  content: '';
  position: absolute;
  inset: -20px;
  background: radial-gradient(circle, rgba(var(--v-theme-primary), 0.1) 0%, transparent 70%);
  animation: ripple 3s ease-out infinite;
}

@keyframes ripple {
  0% {
    transform: scale(0.8);
    opacity: 1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

/* Service Details */
.service-details code {
  background: rgba(var(--v-theme-primary), 0.08);
  padding: 2px 8px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 0.875rem;
}

/* List View Row Hover */
.service-row {
  transition: background-color 0.2s ease;
}

.service-row:hover {
  background-color: rgba(var(--v-theme-primary), 0.02);
}
</style>
