<!-- src/pages/service/ServiceHome.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>Service Calls</li>
        </ul>
      </div>
      <!-- Page Header with Stats -->
      <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="M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437l1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008z" />
              </svg>
            </div>
            Service Calls
          </h1>
          <p class="text-base-content/60 mt-1 ml-13">Manage upcoming and active service calls</p>
        </div>

        <!-- Quick Stats -->
        <div class="flex flex-wrap gap-3">
          <div class="stat-pill">
            <span class="stat-pill-value">{{ services.length }}</span>
            <span class="stat-pill-label">Active Calls</span>
          </div>
        </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 calls...</p>
        </div>

        <!-- Empty State -->
        <div v-else-if="services.length === 0" class="text-center p-10">
          <p>No active service calls 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>Date / Time</th>
                  <th>Address</th>
                  <th>Service Type</th>
                  <th>Description</th>
                  <th class="text-right">Amount</th>
                  <th class="text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="service in services" :key="service.id" class="table-row-hover">
                  <td class="align-top">
                    <router-link :to="{ name: 'customerProfile', params: { id: service.customer_id } }"
                      class="group">
                      <div class="font-bold text-base group-hover:text-primary transition-colors">
                        {{ service.customer_name }}
                      </div>
                      <div class="text-xs font-mono opacity-60 flex items-center gap-1">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                        </svg>
                        #{{ service.id }}
                      </div>
                    </router-link>
                  </td>
                  <td>
                    <div class="font-medium">{{ formatDate(service.scheduled_date) }}</div>
                    <div class="text-xs opacity-70">{{ formatTime(service.scheduled_date) }}</div>
                  </td>
                  <td class="align-top">
                    <div class="flex flex-col">
                      <span class="font-medium text-sm">{{ service.customer_address }}</span>
                      <div class="flex items-center gap-1">
                        <span class="text-xs opacity-70">{{ service.customer_town }}, {{ getStateAbbr(service.customer_state) }} {{ service.customer_zip }}</span>
                        <a :href="`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(`${service.customer_address}, ${service.customer_town}, ${getStateAbbr(service.customer_state)} ${service.customer_zip}`)}`"
                          target="_blank"
                          class="btn btn-xs btn-circle btn-ghost text-base-content/60 hover:text-primary hover:bg-primary/10"
                          title="View on Google Maps">
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" />
                          </svg>
                        </a>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span class="badge badge-sm border-0 text-white font-medium shadow-sm"
                      :style="{ 'background-color': getServiceTypeColor(service.type_service_call) }">
                      {{ getServiceTypeName(service.type_service_call) }}
                    </span>
                  </td>
                  <td class="whitespace-normal text-sm align-top text-white">
                    <!-- TRUNCATION LOGIC FOR DESKTOP -->
                    <div v-if="!isLongDescription(service.description) || isExpanded(service.id)">
                      {{ service.description }}
                      <a v-if="isLongDescription(service.description)" @click.prevent="toggleExpand(service.id)"
                        href="#" class="link link-info link-hover text-xs ml-1 whitespace-nowrap">Show less</a>
                    </div>
                    <div v-else>
                      {{ truncateDescription(service.description) }}
                      <a @click.prevent="toggleExpand(service.id)" href="#"
                        class="link link-info link-hover text-xs ml-1 whitespace-nowrap">Read more</a>
                    </div>
                  </td>
                  <td class="text-right font-mono align-top text-white">{{ formatCurrency(service.service_cost) }}</td>
                  <td class="text-right align-top">
                    <div class="flex items-center justify-end gap-1">
                      <button @click="openEditModal(service)" class="btn btn-xs btn-info btn-outline">Edit</button>
                      <router-link v-if="shouldShowChargeButton(service)"
                        :to="{ name: 'payService', params: { id: service.id } }"
                        class="btn btn-xs btn-success btn-outline">Charge</router-link>
                      <router-link v-if="shouldShowCaptureButton(service)"
                        :to="{ name: 'chargeServiceAuthorize', params: { id: service.id } }"
                        class="btn btn-xs btn-warning btn-outline">Capture</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="service in services" :key="service.id" class="mobile-card">
              <div class="p-3">
                <div class="flex justify-between items-start">
                  <div>
                    <router-link :to="{ name: 'customerProfile', params: { id: service.customer_id } }"
                      class="text-base font-bold link link-hover">
                      {{ service.customer_name }}
                    </router-link>
                    <p class="text-xs text-base-content/60">ID: {{ service.id }}</p>
                  </div>
                  <div class="badge badge-sm border-0 text-white font-medium shadow-sm"
                    :style="{ 'background-color': getServiceTypeColor(service.type_service_call) }">
                    {{ getServiceTypeName(service.type_service_call) }}
                  </div>
                </div>

                <div class="text-sm mt-3 grid grid-cols-2 gap-x-4 gap-y-2">
                  <div>
                    <p class="text-xs text-base-content/50">Address</p>
                    <p class="font-medium">{{ service.customer_address }}</p>
                    <p class="text-xs">{{ service.customer_town }}</p>
                  </div>
                  <div>
                    <p class="text-xs text-base-content/50">Cost</p>
                    <p class="font-mono">{{ formatCurrency(service.service_cost) }}</p>
                  </div>
                  <div class="col-span-2">
                    <p class="text-xs text-base-content/50">Date</p>
                    <p class="font-medium">{{ formatDate(service.scheduled_date) }} <span
                        class="text-xs opacity-60 ml-1">{{ formatTime(service.scheduled_date) }}</span></p>
                  </div>
                </div>

                <!-- TRUNCATION LOGIC FOR MOBILE -->
                <div v-if="service.description" class="text-sm mt-3 p-2 bg-base-200/50 rounded-md">
                  <div v-if="!isLongDescription(service.description) || isExpanded(service.id)">
                    {{ service.description }}
                    <a v-if="isLongDescription(service.description)" @click.prevent="toggleExpand(service.id)" href="#"
                      class="link link-info link-hover text-xs ml-1 whitespace-nowrap">Show less</a>
                  </div>
                  <div v-else>
                    {{ truncateDescription(service.description) }}
                    <a @click.prevent="toggleExpand(service.id)" href="#"
                      class="link link-info link-hover text-xs ml-1 whitespace-nowrap">Read more</a>
                  </div>
                </div>

                <div class="flex gap-2 pt-3 mt-3 border-t border-base-content/10 flex-wrap">
                  <button @click="openEditModal(service)" class="btn btn-sm btn-info btn-outline flex-1">Edit</button>
                  <router-link v-if="shouldShowChargeButton(service)"
                    :to="{ name: 'payService', params: { id: service.id } }"
                    class="btn btn-sm btn-success btn-outline flex-1">Charge</router-link>
                  <router-link v-if="shouldShowCaptureButton(service)"
                    :to="{ name: 'chargeServiceAuthorize', params: { id: service.id } }"
                    class="btn btn-sm btn-warning btn-outline flex-1">Capture</router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>



  <ServiceEditModal v-if="selectedServiceForEdit" :service="selectedServiceForEdit" @close-modal="closeEditModal"
    @save-changes="handleSaveChanges" @delete-service="handleDeleteService" />
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { serviceService } from '../../services/serviceService'
import { authService } from '../../services/authService'
import { ServiceCall } from '../../types/models'
import ServiceEditModal from './ServiceEditModal.vue'
import dayjs from 'dayjs';

// Reactive data
const user = ref(null)
const services = ref<ServiceCall[]>([])
const isLoading = ref(true)
const selectedServiceForEdit = ref<ServiceCall | null>(null)
// --- ADDITIONS FOR TRUNCATION ---
const wordLimit = ref(50)
const expandedIds = ref<number[]>([])

// State abbreviation mapping
const STATE_ABBR_MAP: { [key: number]: string } = {
  0: 'MA', 1: 'RI', 2: 'NH', 3: 'ME', 4: 'VT', 5: 'CT', 6: 'NY', 7: 'NJ',
  8: 'PA', 9: 'DE', 10: 'MD', 11: 'DC', 12: 'VA', 13: 'WV', 14: 'NC',
  15: 'SC', 16: 'GA', 17: 'FL', 18: 'AL', 19: 'MS', 20: 'TN', 21: 'KY',
  22: 'OH', 23: 'IN', 24: 'MI', 25: 'IL', 26: 'WI', 27: 'MN', 28: 'IA',
  29: 'MO', 30: 'AR', 31: 'LA', 32: 'TX', 33: 'OK', 34: 'KS', 35: 'NE',
  36: 'SD', 37: 'ND', 38: 'MT', 39: 'WY', 40: 'CO', 41: 'NM', 42: 'AZ',
  43: 'UT', 44: 'NV', 45: 'ID', 46: 'WA', 47: 'OR', 48: 'CA', 49: 'AK', 50: 'HI'
}

const getStateAbbr = (stateId: number | string | undefined): string => {
  if (stateId === undefined) return 'MA';
  const id = typeof stateId === 'string' ? parseInt(stateId) : stateId;
  return STATE_ABBR_MAP[id] || 'MA';
}

// Lifecycle
onMounted(() => {
  userStatus();
  fetchUpcomingServices();
})

// Functions
const fetchUpcomingServices = async (): Promise<void> => {
  isLoading.value = true;
  try {
    const response = await serviceService.getUpcoming();
    if (response.data.ok) {
      const serviceList = response.data.services || [];
      services.value = serviceList.sort((a: ServiceCall, b: ServiceCall) => b.id - a.id);
    }
  } catch (error) {
    console.error("Failed to fetch upcoming service calls:", 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 openEditModal = (service: ServiceCall) => {
  selectedServiceForEdit.value = service;
}

const closeEditModal = () => {
  selectedServiceForEdit.value = null;
}

const isLongDescription = (text: string): boolean => {
  if (!text) return false;
  return text.split(/\s+/).length > wordLimit.value;
}

const truncateDescription = (text: string): string => {
  if (!isLongDescription(text)) return text;
  const words = text.split(/\s+/);
  return words.slice(0, wordLimit.value).join(' ') + '...';
}

const isExpanded = (id: number): boolean => {
  return expandedIds.value.includes(id);
}

const toggleExpand = (id: number): void => {
  const index = expandedIds.value.indexOf(id);
  if (index === -1) {
    expandedIds.value.push(id);
  } else {
    expandedIds.value.splice(index, 1);
  }
}

const handleSaveChanges = async (updatedService: ServiceCall) => {
  try {
    const response = await serviceService.update(updatedService.id, updatedService);
    if (response.data.ok) {
      const index = services.value.findIndex(s => s.id === updatedService.id);
      if (index !== -1) {
        services.value[index] = response.data.service;
      }
      closeEditModal();
    }
  } catch (error) {
    console.error("Failed to save changes:", error);
    alert("An error occurred while saving. Please check the console.");
  }
}

const handleDeleteService = async (serviceId: number) => {
  try {
    const response = await serviceService.delete(serviceId);
    if (response.data.ok) {
      services.value = services.value.filter(s => s.id !== serviceId);
      closeEditModal();
    }
  } catch (error) {
    console.error("Failed to delete service call:", error);
    alert("An error occurred while deleting. Please check the console.");
  }
}

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

const formatTime = (dateString: string): string => {
  if (!dateString) return 'N/A';
  return dayjs(dateString).format('h:mm A');
}

const getServiceTypeName = (typeId: number): string => {
  const typeMap: { [key: number]: string } = {
    0: 'Tune-up',
    1: 'No Heat',
    2: 'Fix',
    3: 'Tank Install',
    4: 'Other',
  };
  return typeMap[typeId] || 'Unknown Service';
}

const formatCurrency = (value: string | number): string => {
  if (value === null || value === undefined || value === '') return '$0.00';
  const numberValue = Number(value);
  if (isNaN(numberValue)) return '$0.00';

  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(numberValue);
}

const getServiceTypeColor = (typeId: number): string => {
  const colorMap: { [key: number]: string } = {
    0: 'blue',
    1: 'red',
    2: 'green',
    3: '#B58900',
    4: 'black',
  };
  return colorMap[typeId] || 'gray';
}

const shouldShowChargeButton = (service: any): boolean => {
  return service.payment_status === null || service.payment_status === undefined;
}

const shouldShowCaptureButton = (service: any): boolean => {
  return service.payment_status === 1;
}
</script>
