<!-- src/pages/service/ServicePlans.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs & Title -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li><router-link :to="{ name: 'ServiceHome' }">Service</router-link></li>
          <li>Service Plans</li>
        </ul>
      </div>
      <!-- Page Header -->
      <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mt-4 mb-6">
        <div>
          <h1 class="text-2xl md:text-3xl font-bold flex items-center gap-3">
            <div
              class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-primary/60 flex items-center justify-center shadow-lg">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
                stroke="currentColor" class="w-5 h-5 text-primary-content">
                <path stroke-linecap="round" stroke-linejoin="round"
                  d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
              </svg>
            </div>
            Service Plans
          </h1>
          <p class="text-base-content/60 mt-1 ml-13">Manage active service contracts and agreements</p>
        </div>

        <div v-if="!isLoading" class="stat-pill">
          <span class="stat-pill-value">{{ servicePlans.length }}</span>
          <span class="stat-pill-label">Contracts</span>
        </div>
      </div>

      <!-- Main Content Card -->
      <div class="modern-table-card">

        <!-- Loading State -->
        <div v-if="isLoading" class="text-center p-10">
          <span class="loading loading-spinner loading-lg"></span>
          <p class="mt-2">Loading service plans...</p>
        </div>

        <!-- Empty State -->
        <div v-else-if="servicePlans.length === 0" class="text-center p-10">
          <p>No active service contracts found.</p>
        </div>

        <!-- Data Display -->
        <div v-else>
          <!-- DESKTOP VIEW: Table -->
          <div class="overflow-x-auto hidden xl:block">
            <table class="modern-table">
              <thead>
                <tr>
                  <th>Customer</th>
                  <th>Plan Type</th>
                  <th>Contract Years</th>
                  <th>Start Date</th>
                  <th>End Date</th>
                  <th>Status</th>
                  <th class="text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="plan in servicePlans" :key="plan.id" class="table-row-hover">
                  <td class="align-top">
                    <div class="font-bold">{{ plan.customer_name }}</div>
                    <div class="text-sm opacity-70">{{ plan.customer_address }}, {{ plan.customer_town }}</div>
                  </td>
                  <td class="align-top">
                    <span class="badge badge-sm text-white"
                      :style="{ 'background-color': getPlanColor(plan.contract_plan) }">
                      {{ getPlanName(plan.contract_plan) }}
                    </span>
                  </td>
                  <td class="align-top">{{ plan.contract_years }} year{{ plan.contract_years > 1 ? 's' : '' }}</td>
                  <td class="align-top">{{ formatDate(plan.contract_start_date) }}</td>
                  <td class="align-top">{{ formatEndDate(plan.contract_start_date, plan.contract_years) }}</td>
                  <td class="align-top">
                    <span class="badge badge-sm" :class="getStatusBadge(plan.contract_start_date, plan.contract_years)">
                      {{ getStatusText(plan.contract_start_date, plan.contract_years) }}
                    </span>
                  </td>
                  <td class="text-right align-top">
                    <div class="flex items-center justify-end gap-1">
                      <router-link :to="{ name: 'customerProfile', params: { id: plan.customer_id } }"
                        class="btn btn-xs btn-ghost">Profile</router-link>
                      <router-link :to="{ name: 'servicePlanEdit', params: { id: plan.customer_id } }"
                        class="btn btn-xs btn-info btn-outline">Edit</router-link>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- MOBILE VIEW: Cards -->
          <div class="xl:hidden space-y-4 px-4 pb-4">
            <div v-for="plan in servicePlans" :key="plan.id" class="mobile-card">
              <div class="p-3">
                <div class="flex justify-between items-start">
                  <div>
                    <h2 class="font-bold text-base">{{ plan.customer_name }}</h2>
                    <p class="text-xs text-base-content/60">{{ plan.customer_address }}, {{ plan.customer_town }}</p>
                  </div>
                  <div class="badge badge-sm text-white"
                    :style="{ 'background-color': getPlanColor(plan.contract_plan) }">
                    {{ getPlanName(plan.contract_plan) }}
                  </div>
                </div>

                <div class="text-sm mt-3 grid grid-cols-2 gap-x-4 gap-y-2">
                  <p><strong class="font-semibold">Years:</strong> {{ plan.contract_years }}</p>
                  <p><strong class="font-semibold">Start:</strong> {{ formatDate(plan.contract_start_date) }}</p>
                  <p><strong class="font-semibold">End:</strong> {{ formatEndDate(plan.contract_start_date,
                    plan.contract_years) }}</p>
                  <p><strong class="font-semibold">Status:</strong>
                    <span class="badge badge-sm ml-1"
                      :class="getStatusBadge(plan.contract_start_date, plan.contract_years)">
                      {{ getStatusText(plan.contract_start_date, plan.contract_years) }}
                    </span>
                  </p>
                </div>

                <div class="flex gap-2 pt-3 mt-3 border-t border-base-content/10 flex-wrap">
                  <router-link :to="{ name: 'customerProfile', params: { id: plan.customer_id } }"
                    class="btn btn-sm btn-ghost flex-1">View Profile</router-link>
                  <router-link :to="{ name: 'servicePlanEdit', params: { id: plan.customer_id } }"
                    class="btn btn-sm btn-info btn-outline flex-1">Edit Contract</router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>


</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import serviceService from '../../services/serviceService'
import authService from '../../services/authService'
import { ServicePlan } from '../../types/models'
import dayjs from 'dayjs';

// Reactive data
const user = ref<any>(null)
const servicePlans = ref<ServicePlan[]>([])
const isLoading = ref(true)

// Lifecycle
onMounted(() => {
  if (authService) {
    userStatus();
  }
  fetchServicePlans();
})

// Functions
const fetchServicePlans = async (): Promise<void> => {
  isLoading.value = true;
  try {
    const response = await serviceService.plans.getActive();
    if (response.data && response.data.plans) {
      servicePlans.value = response.data.plans;
    } else {
      servicePlans.value = [];
    }
  } catch (error) {
    console.error("Failed to fetch service plans:", error);
  } finally {
    isLoading.value = false;
  }
}

const userStatus = () => {
  authService.whoami()
    .then((response: any) => {
      if (response.data.ok) {
        user.value = response.data.user;
      }
    })
    .catch(() => {
      user.value = null
    })
}

const getPlanName = (planType: number): string => {
  const planNames: { [key: number]: string } = {
    1: 'Standard',
    2: 'Premium'
  };
  return planNames[planType] || 'Unknown';
}

const getPlanColor = (planType: number): string => {
  const planColors: { [key: number]: string } = {
    1: 'blue',
    2: 'gold'
  };
  return planColors[planType] || 'gray';
}

const formatDate = (dateString: string): string => {
  if (!dateString) return 'N/A';
  return dayjs(dateString).format('MMM D, YYYY');
}

const formatEndDate = (startDate: string, years: number): string => {
  if (!startDate) return 'N/A';
  return dayjs(startDate).add(years, 'year').format('MMM D, YYYY');
}

const getStatusText = (startDate: string, years: number): string => {
  if (!startDate) return 'Unknown';
  const endDate = dayjs(startDate).add(years, 'year');
  const now = dayjs();
  if (now.isAfter(endDate)) {
    return 'Expired';
  } else if (now.isAfter(endDate.subtract(30, 'day'))) {
    return 'Expiring Soon';
  } else {
    return 'Active';
  }
}

const getStatusBadge = (startDate: string, years: number): string => {
  if (!startDate) return 'badge-ghost';
  const endDate = dayjs(startDate).add(years, 'year');
  const now = dayjs();
  if (now.isAfter(endDate)) {
    return 'badge-error';
  } else if (now.isAfter(endDate.subtract(30, 'day'))) {
    return 'badge-warning';
  } else {
    return 'badge-success';
  }
}
</script>
