<!-- src/pages/service/calender/CalendarCustomer.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 v-if="customer">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</li>
          <li>Service Calendar</li>
        </ul>
      </div>

      <!-- 
        Main Responsive Container:
        - Stacks vertically on mobile (flex-col)
        - Sits side-by-side on large screens (lg:flex-row)
      -->
      <div class="flex flex-col lg:flex-row gap-6 mt-6">
        
        <!-- Sidebar Area (Uses our new responsive EventSidebar) -->
        <EventSidebar v-if="!isLoading && customer" :customer="customer" :selected-date="selectedDate" @event-scheduled="handleEventScheduled" />
        
        <!-- Loading/Error States (Styled to match the sidebar) -->
        <div v-else class="w-full lg:w-96 lg:flex-none p-4">
          <div class="bg-neutral rounded-lg p-6 sticky top-4 text-center">
            <div v-if="isLoading">
              <span class="loading loading-spinner"></span>
              <p class="mt-2">Loading Customer...</p>
            </div>
            <div v-else>
              <h2 class="text-xl font-bold text-error">Error</h2>
              <p>Could not load customer data. You can still view the master calendar.</p>
            </div>
          </div>
        </div>

        <!-- Main Calendar Area -->
        <div class="flex-grow bg-neutral rounded-lg p-4">
          <FullCalendar ref="fullCalendar" :options="calendarOptions" />
        </div>

      </div>
    </div>
  </div>

  <!-- Modal remains at the root level, which is correct -->
  <ServiceEditModal
    v-if="selectedServiceForEdit"
    :service="selectedServiceForEdit"
    @close-modal="closeEditModal"
    @save-changes="handleSaveChanges"
    @delete-service="handleDeleteService"
  />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import Header from '../../../layouts/headers/headerauth.vue';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import { CalendarOptions, EventClickArg } from '@fullcalendar/core';
import EventSidebar from './EventSidebar.vue';
import ServiceEditModal from '../../service/ServiceEditModal.vue';
import serviceService from '../../../services/serviceService';
import customerService from '../../../services/customerService';
import { notify } from '@kyvg/vue3-notification';

const fullCalendar = ref<InstanceType<typeof FullCalendar> | null>(null);

interface ServiceCall { id: number; scheduled_date: string; customer_id: number; customer_name: string; customer_address: string; customer_town: string; type_service_call: number; description: string; service_cost: string;}
interface Customer { id: number; customer_last_name: string; customer_first_name: string; customer_town: string; customer_state: number; customer_zip: string; customer_phone_number: string; customer_address: string; customer_home_type: number; customer_apt: string; }

// Route
const route = useRoute();

// Functions declared first (needed for calendarOptions)
const handleEventClick = (clickInfo: EventClickArg): void => {
  const events = (calendarOptions.value.events as any[]) || [];
  const originalEvent = events.find(e => e.id == clickInfo.event.id);

  if (originalEvent) {
      // We "flatten" the nested object from the calendar into the simple,
      // flat structure that the modal expects, ensuring customer_id is included.
      selectedServiceForEdit.value = {
          id: originalEvent.id,
          scheduled_date: originalEvent.start,
          customer_id: originalEvent.customer_id, // This was the missing piece
          customer_name: originalEvent.title.split(': ')[1] || 'Unknown Customer',
          type_service_call: originalEvent.extendedProps.type_service_call,
          description: originalEvent.extendedProps.description,
          service_cost: originalEvent.extendedProps.description,
          customer_address: '',
          customer_town: '',
      };
  }
};

// Reactive data
const isLoading = ref(false);
const selectedDate = ref('');
const selectedDayEl = ref<HTMLElement | null>(null);
const selectedServiceForEdit = ref<Partial<ServiceCall> | null>(null);
const calendarOptions = ref<CalendarOptions>({
  plugins: [dayGridPlugin, interactionPlugin],
  initialView: 'dayGridMonth',
  weekends: true,
  events: [] as any[],
  eventClick: handleEventClick,
  dateClick: (info: any) => {
    if (selectedDayEl.value) selectedDayEl.value.classList.remove('fc-date-selected');
    selectedDate.value = info.dateStr;
    selectedDayEl.value = info.dayEl;
    info.dayEl.classList.add('fc-date-selected');
  },
});
const customer = ref<Customer | null>(null);

// Functions (defined before watchers to avoid hoisting issues)
const closeEditModal = () => {
    selectedServiceForEdit.value = null;
};

const getCustomer = async (customerId: string): Promise<void> => {
  isLoading.value = true;
  customer.value = null;
  try {
    const response = await customerService.getById(Number(customerId));
    const customerData = response.data?.customer || response.data;
    if (customerData && (customerData as any).id) {
      customer.value = customerData as unknown as Customer;
    }
  } catch (error) {
    console.error("API call to get customer FAILED:", error);
  } finally {
    isLoading.value = false;
  }
};

const fetchEvents = async (): Promise<void> => {
  try {
    const response = await serviceService.getAll();
    const events = response.data?.events || [];
    calendarOptions.value.events = events;
    const api = fullCalendar.value?.getApi();
    if (api) {
      api.removeAllEvents();
      events.forEach((e: any) => api.addEvent(e));
    }
  } catch (error) {
    console.error("Error fetching all calendar events:", error);
  }
};

const handleSaveChanges = async (updatedService: ServiceCall) => {
  try {
    await serviceService.update(updatedService.id, updatedService);
    await fetchEvents();
    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 === true) {
        await fetchEvents();
        closeEditModal();
    } else {
        // console.error("Failed to delete event:", response.data.error); 
        // Error property might not exist on typed response, but checking ok is enough
    }
  } catch (error) {
    console.error("Error deleting event:", error);
  }
};

const handleEventScheduled = async (eventData: any): Promise<void> => {
  if (!customer.value) {
      alert("Error: A customer must be loaded in the sidebar to create a new event.");
      return;
  }
  try {
    const payload = {
      expected_delivery_date: eventData.start, type_service_call: eventData.type_service_call,
      customer_id: customer.value.id, description: eventData.extendedProps.description,
    };
    const response = await serviceService.create(payload);

    if (response.data.ok) {
      await fetchEvents();
      notify({ title: 'Service Call Added', text: 'The service call has been scheduled.', type: 'success' });
    } else {
      notify({ title: 'Error', text: 'Failed to create service call.', type: 'error' });
    }
  } catch (error) {
    console.error("Error creating event:", error);
    notify({ title: 'Error', text: 'An error occurred while scheduling the service call.', type: 'error' });
  }
};

const handleEventDelete = async (eventId: string): Promise<void> => {
    // This is a simple alias now, as handleDeleteService is more specific
    await handleDeleteService(Number(eventId));
};

// Watchers (after function definitions)
watch(() => route.params.id, (newId) => {
  if (newId) getCustomer(newId as string);
}, { immediate: true });

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

<style scoped>
:deep(.fc-date-selected) {
  background-color: rgba(59, 130, 246, 0.2) !important;
}
</style>