<!-- src/pages/customer/ServicePlanEdit.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: 'customer' }">Customers</router-link></li>
          <li><router-link :to="{ name: 'customerProfile', params: { id: customerId } }">
            {{ customerName }}
          </router-link></li>
          <li>Service Plan</li>
        </ul>
      </div>

      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mt-4">
        <h1 class="text-3xl font-bold">
          Service Plan: {{ customerName }}
        </h1>
        <router-link :to="{ name: 'customerProfile', params: { id: customerId } }" class="btn btn-secondary btn-sm mt-2 sm:mt-0">
          Back to Profile
        </router-link>
      </div>

      <!-- Main Form Card -->
      <div class="bg-neutral rounded-lg p-6 mt-6">
        <form @submit.prevent="onSubmit" class="space-y-6">

          <!-- Current Plan Status -->
          <div v-if="servicePlan && servicePlan.contract_plan > 0" class="alert alert-info">
            <div class="flex items-center">
              <div class="flex-1">
                <h3 class="font-bold">Current Plan: {{ getPlanName(servicePlan.contract_plan) }}</h3>
                <p>{{ servicePlan.contract_years }} Year{{ servicePlan.contract_years > 1 ? 's' : '' }} Contract</p>
                <p class="text-sm">Expires: {{ formatEndDate(servicePlan.contract_start_date, servicePlan.contract_years) }}</p>
              </div>
              <div class="badge" :class="getStatusBadge(servicePlan.contract_start_date, servicePlan.contract_years)">
                {{ getStatusText(servicePlan.contract_start_date, servicePlan.contract_years) }}
              </div>
            </div>
          </div>

          <!-- Service Plan Form -->
          <div>
            <h2 class="text-lg font-bold">Service Plan Details</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

              <!-- Contract Plan -->
              <div class="form-control">
                <label class="label"><span class="label-text">Service Plan</span></label>
                <select v-model="formData.contract_plan" class="select select-bordered select-sm w-full" required>
                  <option value="0">No Contract</option>
                  <option value="1">Standard Plan</option>
                  <option value="2">Premium Plan</option>
                </select>
              </div>

              <!-- Contract Years -->
              <div class="form-control">
                <label class="label"><span class="label-text">Contract Years</span></label>
                <input v-model.number="formData.contract_years" type="number" min="1" placeholder="1"
                       class="input input-bordered input-sm w-full" required />
              </div>

              <!-- Contract Start Date -->
              <div class="form-control">
                <label class="label"><span class="label-text">Contract Start Date</span></label>
                <input v-model="formData.contract_start_date" type="date"
                       class="input input-bordered input-sm w-full" required />
              </div>

              <!-- Contract End Date (Calculated) -->
              <div class="form-control">
                <label class="label"><span class="label-text">Contract End Date</span></label>
                <input :value="formatEndDate(formData.contract_start_date, formData.contract_years)"
                       type="text" readonly class="input input-bordered input-sm w-full bg-gray-100" />
              </div>

            </div>
          </div>

          <!-- Renewal Section (only show if there's an existing plan) -->
          <div v-if="servicePlan && servicePlan.contract_plan > 0">
            <h2 class="text-lg font-bold">Contract Renewal</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="form-control">
                <label class="label"><span class="label-text">Renewal Date</span></label>
                <input v-model="renewalDate" type="date" placeholder="Select renewal date"
                       class="input input-bordered input-sm w-full" />
              </div>
              <div class="form-control">
                <label class="label"><span class="label-text">&nbsp;</span></label>
                <button @click="renewContract" type="button" class="btn btn-sm btn-success w-full">
                  Renew Contract (+1 Year)
                </button>
              </div>
            </div>
            <p class="text-xs text-gray-500 mt-2">
              This will add +1 year to the contract and update the start date to the renewal date.
            </p>
          </div>

          <!-- Action Buttons -->
          <div class="pt-4 flex gap-4">
            <button type="submit" class="btn btn-primary btn-sm">
              {{ servicePlan ? 'Update Plan' : 'Create Plan' }}
            </button>
            <button v-if="servicePlan" @click="deletePlan" type="button" class="btn btn-error btn-sm">
              Delete Plan
            </button>
          </div>

        </form>
      </div>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { customerService } from '../../services/customerService'
import { serviceService } from '../../services/serviceService'
import { ServicePlan, Customer } from '../../types/models'
import { notify } from "@kyvg/vue3-notification";

const route = useRoute()
const router = useRouter()

// Reactive data
const customerId = ref(route.params.id as string)
const customerName = ref('')
const servicePlan = ref(null as ServicePlan | null)
const formData = ref({
  contract_plan: 0,
  contract_years: 1,
  contract_start_date: '',
})
const renewalDate = ref('')

// Computed
const computedEndDate = computed(() => {
  return (startDate: string, years: number): string => {
    if (!startDate) return 'N/A';
    const date = new Date(startDate);
    date.setFullYear(date.getFullYear() + years);
    return date.toISOString().split('T')[0];
  }
})

// Functions
const loadCustomer = async () => {
  try {
    const response = await customerService.getById(parseInt(customerId.value));
    const customer: Customer = response.data?.customer || response.data;
    customerName.value = `${customer.customer_first_name} ${customer.customer_last_name}`;
  } catch (error) {
    console.error('Failed to load customer:', error);
    notify({ title: "Error", text: "Failed to load customer information.", type: "error" });
  }
}

const loadServicePlan = async () => {
  try {
    const response = await serviceService.plans.getForCustomer(parseInt(customerId.value));
    const plan = response.data?.plan || response.data;
    if (plan && plan.contract_plan !== undefined) {
      servicePlan.value = plan;
      formData.value = {
        contract_plan: plan.contract_plan,
        contract_years: plan.contract_years,
        contract_start_date: plan.contract_start_date,
      };
    }
  } catch (error) {
    console.log('No existing service plan found');
  }
}

const onSubmit = async () => {
  try {
    const payload = {
      customer_id: parseInt(customerId.value),
      ...formData.value
    };

    let response;
    if (servicePlan.value) {
      response = await serviceService.plans.update(parseInt(customerId.value), payload);
    } else {
      response = await serviceService.plans.create(payload);
    }

    if (response.data.ok) {
      notify({
        title: "Success",
        text: `Service plan ${servicePlan.value ? 'updated' : 'created'} successfully!`,
        type: "success"
      });
      router.push({ name: 'customerProfile', params: { id: customerId.value } });
    }
  } catch (error) {
    console.error('Failed to save service plan:', error);
    notify({ title: "Error", text: "Failed to save service plan.", type: "error" });
  }
}

const deletePlan = async () => {
  if (!confirm('Are you sure you want to delete this service plan?')) return;

  try {
    const response = await serviceService.plans.delete(parseInt(customerId.value));

    if (response.data.ok) {
      notify({ title: "Success", text: "Service plan deleted successfully!", type: "success" });
      servicePlan.value = null;
      formData.value = {
        contract_plan: 0,
        contract_years: 1,
        contract_start_date: '',
      };
    }
  } catch (error) {
    console.error('Failed to delete service plan:', error);
    notify({ title: "Error", text: "Failed to delete service plan.", type: "error" });
  }
}

const renewContract = () => {
  if (!renewalDate.value) {
    notify({ title: "Error", text: "Please select a renewal date.", type: "error" });
    return;
  }

  formData.value.contract_years += 1;
  formData.value.contract_start_date = renewalDate.value;
  renewalDate.value = '';

  notify({
    title: "Success",
    text: "Contract renewed! Years increased by 1 and start date updated.",
    type: "success"
  });
}

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

const formatEndDate = (startDate: string, years: number): string => {
  if (!startDate) return 'N/A';
  const date = new Date(startDate);
  date.setFullYear(date.getFullYear() + years);
  return date.toISOString().split('T')[0];
}

const getStatusText = (startDate: string, years: number): string => {
  if (!startDate) return 'Unknown';
  const endDate = new Date(startDate);
  endDate.setFullYear(endDate.getFullYear() + years);
  const now = new Date();
  if (now > endDate) {
    return 'Expired';
  } else if (now > new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000)) {
    return 'Expiring Soon';
  } else {
    return 'Active';
  }
}

const getStatusBadge = (startDate: string, years: number): string => {
  if (!startDate) return 'badge-ghost';
  const endDate = new Date(startDate);
  endDate.setFullYear(endDate.getFullYear() + years);
  const now = new Date();
  if (now > endDate) {
    return 'badge-error';
  } else if (now > new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000)) {
    return 'badge-warning';
  } else {
    return 'badge-success';
  }
}

// Lifecycle
onMounted(() => {
  loadCustomer();
  loadServicePlan();
})
</script>
