<!-- src/pages/service/calender/EventSidebar.vue -->
<template>
  <!-- 
    This container is now responsive. It's full-width on mobile 
    and becomes a fixed-width sidebar on large screens.
  -->
  <div class="w-full lg:w-96 lg:flex-none p-4">
    <!-- The sidebar is now sticky to the top on large screens -->
    <div class="bg-neutral rounded-lg p-6 sticky top-4">
      <h2 class="text-xl font-bold mb-4">Schedule Service</h2>
      
      <form @submit.prevent="submitEvent" class="space-y-4">
        <!-- Service Type -->
        <div class="form-control">
          <label class="label"><span class="label-text">Type of Service</span></label>
          <select class="select select-bordered select-sm w-full" v-model="selectedService" required>
            <option disabled value="">Please select one</option>
            <option v-for="option in serviceOptions" :key="option.value" :value="option.value">
              {{ option.text }}
            </option>
          </select>
        </div>

        <!-- Description -->
        <div class="form-control">
          <label class="label"><span class="label-text">Description</span></label>
          <textarea v-model="event.description" rows="3" required class="textarea textarea-bordered textarea-sm" placeholder="Notes for the technician..."></textarea>
        </div>

        <!-- Date & Time Grid -->
        <div class="grid grid-cols-2 gap-4">
          <!-- Date -->
          <div class="form-control">
            <label class="label"><span class="label-text">Date</span></label>
            <input type="date" v-model="event.date" required class="input input-bordered input-sm w-full">
          </div>
          <!-- Time -->
          <div class="form-control">
            <label class="label"><span class="label-text">Time</span></label>
            <select v-model="event.time" class="select select-bordered select-sm w-full">
              <option v-for="hour in 24" :key="hour" :value="hour - 1">{{ (hour - 1).toString().padStart(2, '0') }}:00</option>
            </select>
          </div>
        </div>

        <!-- Quick Time Buttons -->
        <div class="grid grid-cols-5 gap-2">
          <button v-for="qt in quickTimes" :key="qt.hour" type="button"
            class="btn btn-sm"
            :class="event.time === qt.hour ? 'btn-primary' : 'btn-outline'"
            @click="event.time = qt.hour">
            {{ qt.label }}
          </button>
        </div>

        <button type="submit" class="btn btn-warning btn-sm w-full mt-4">
          Add Event
        </button>
      </form>

      <!-- Customer Info Section -->
      <div v-if="customer" class="mt-6">
        <div class="divider">For Customer</div>
        <!-- Customer Info "Card within a Card" -->
        <div class="card bg-base-100 shadow-md">
            <div class="card-body p-4">
                <h3 class="card-title text-base">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</h3>
                <div class="text-sm mt-2 space-y-1">
                    <p>{{ customer.customer_address }}</p>
                    <p v-if="customer.customer_apt && customer.customer_apt !== 'None'">{{ customer.customer_apt }}</p>
                    <p>{{ customer.customer_town }}, {{ customerStateName }} {{ customer.customer_zip }}</p>
                    <p class="pt-2 font-semibold">{{ customer.customer_phone_number }}</p>
                </div>
                <div class="card-actions justify-end">
                    <div class="badge badge-outline">{{ customerHomeType }}</div>
                </div>
            </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import dayjs from 'dayjs';

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;
}

// Props
const props = defineProps<{
  customer: Customer | null;
  selectedDate?: string;
}>();

watch(() => props.selectedDate, (date) => {
  if (date) event.value.date = date;
});

// Emits
const emit = defineEmits<{
  'event-scheduled': [eventData: any];
}>();

// Reactive data
const selectedService = ref<string | number>('');
const serviceOptions = ref([
  { text: 'Tune-up', value: 0 },
  { text: 'No Heat', value: 1 },
  { text: 'Fix', value: 2 },
  { text: 'Tank Install', value: 3 },
  { text: 'Other', value: 4 },
]);
const event = ref({
  description: '',
  date: dayjs().format('YYYY-MM-DD'),
  endDate: '',
  time: 12,
});

const quickTimes = [
  { label: '7am', hour: 7 },
  { label: '9am', hour: 9 },
  { label: '11am', hour: 11 },
  { label: '1pm', hour: 13 },
  { label: '3pm', hour: 15 },
];

// Computed properties
const customerStateName = computed((): string => {
  if (!props.customer) return '';
  const stateMap: { [key: number]: string } = {
    0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire',
    3: 'Maine', 4: 'Vermont', 5: 'Connecticut', 6: 'New York',
  };
  return stateMap[props.customer.customer_state] || 'Unknown';
});

const customerHomeType = computed((): string => {
  if (!props.customer) return '';
  const homeTypeMap: { [key: number]: string } = {
    0: 'Residential', 1: 'Apartment', 2: 'Condo', 3: 'Commercial',
    4: 'Business', 5: 'Construction', 6: 'Container',
  };
  return homeTypeMap[props.customer.customer_home_type] || 'Unknown';
});

// Functions
const submitEvent = () => {
  if (!props.customer) {
    alert("Cannot submit: No customer data is loaded.");
    return;
  }

  const serviceLabel = serviceOptions.value.find(o => o.value === selectedService.value)?.text || 'Service';
  const autoTitle = `${serviceLabel} - ${props.customer.customer_first_name} ${props.customer.customer_last_name}`;

  const startDateTime = dayjs(`${event.value.date} ${event.value.time}:00`).format('YYYY-MM-DDTHH:mm:ss');
  const endDateTime = event.value.endDate ? dayjs(event.value.endDate).add(1, 'day').format('YYYY-MM-DD') : undefined;

  const eventPayload = {
    title: autoTitle,
    start: startDateTime,
    type_service_call: selectedService.value,
    end: endDateTime,
    extendedProps: {
      description: event.value.description,
    },
  };

  emit('event-scheduled', eventPayload);

  selectedService.value = '';
  event.value.description = '';
  event.value.endDate = '';
  event.value.date = dayjs().format('YYYY-MM-DD');
  event.value.time = 12;
};
</script>
