<!-- src/pages/customer/service/PartsEditModal.vue -->
<template>
  <!-- Modal Overlay -->
  <div class="fixed inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center z-50">
    <!-- Modal Content -->
    <div class="relative bg-base-100 text-base-content p-6 rounded-lg shadow-xl w-full max-w-2xl">
      
      <!-- Modal Header -->
      <div class="flex justify-between items-center border-b border-gray-700 pb-3 mb-4">
        <h3 class="text-2xl font-bold">Edit Equipment Parts</h3>
        <button @click="$emit('close-modal')" type="button" class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
      </div>

      <!-- Form for Editing -->
      <form @submit.prevent="saveChanges">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- Oil Filter 1 Section -->
          <div>
            <label for="oil-filter-1" class="block text-sm font-medium mb-2">Oil Filter 1</label>
            <select id="oil-filter-1" v-model="editableParts.oil_filter" class="select select-bordered w-full">
              <option disabled value="">Select Filter</option>
              <option v-for="item in oilFilterOptions" :key="`filter1-${item}`" :value="item">{{ item }}</option>
            </select>
          </div>

          <!-- Oil Filter 2 Section -->
          <div>
            <label for="oil-filter-2" class="block text-sm font-medium mb-2">Oil Filter 2</label>
            <select id="oil-filter-2" v-model="editableParts.oil_filter_2" class="select select-bordered w-full">
              <option disabled value="">Select Filter</option>
              <option v-for="item in oilFilterOptions" :key="`filter2-${item}`" :value="item">{{ item }}</option>
            </select>
          </div>

          <!-- Hot Water Tank Section -->
          <div class="md:col-span-2 border-t border-gray-700 pt-4">
            <label class="block text-sm font-medium mb-2">Hot Water Tank</label>
            <div class="flex space-x-6">
              <label class="cursor-pointer">
                <input type="radio" :value="1" v-model="editableParts.hot_water_tank" class="radio radio-primary" />
                <span class="ml-2">Yes</span>
              </label>
              <label class="cursor-pointer">
                <input type="radio" :value="0" v-model="editableParts.hot_water_tank" class="radio radio-primary" />
                <span class="ml-2">No</span>
              </label>
            </div>
          </div>

          <!-- Oil Nozzle 1 Section -->
          <div class="md:col-span-2 border-t border-gray-700 pt-4">
            <label class="block text-sm font-medium mb-2">Oil Nozzle 1</label>
            <div class="grid grid-cols-3 gap-2">
              <select v-model="nozzle1.part1" class="select select-bordered w-full">
                <option disabled value="">Type</option>
                <option v-for="item in nozzlePart1Options" :key="`n1p1-${item}`" :value="item">{{ item }}</option>
              </select>
              <select v-model="nozzle1.part2" class="select select-bordered w-full">
                <option disabled value="">Rate</option>
                <option v-for="item in nozzlePart2Options" :key="`n1p2-${item}`" :value="item">{{ item }}</option>
              </select>
              <select v-model="nozzle1.part3" class="select select-bordered w-full">
                <option disabled value="">Angle</option>
                <option v-for="item in nozzlePart3Options" :key="`n1p3-${item}`" :value="item">{{ item }}</option>
              </select>
            </div>
          </div>

          <!-- Oil Nozzle 2 Section -->
          <div class="md:col-span-2 border-t border-gray-700 pt-4">
            <label class="block text-sm font-medium mb-2">Oil Nozzle 2</label>
            <div class="grid grid-cols-3 gap-2">
              <select v-model="nozzle2.part1" class="select select-bordered w-full">
                <option disabled value="">Type</option>
                <option v-for="item in nozzlePart1Options" :key="`n2p1-${item}`" :value="item">{{ item }}</option>
              </select>
              <select v-model="nozzle2.part2" class="select select-bordered w-full">
                <option disabled value="">Rate</option>
                <option v-for="item in nozzlePart2Options" :key="`n2p2-${item}`" :value="item">{{ item }}</option>
              </select>
              <select v-model="nozzle2.part3" class="select select-bordered w-full">
                <option disabled value="">Angle</option>
                <option v-for="item in nozzlePart3Options" :key="`n2p3-${item}`" :value="item">{{ item }}</option>
              </select>
            </div>
          </div>
        </div>
        
        <!-- Action Buttons -->
        <div class="mt-8 flex justify-end space-x-3">
          <button @click.prevent="$emit('close-modal')" type="button" class="btn btn-ghost">Cancel</button>
          <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</template>

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

// Interfaces remain the same
interface ServiceParts {
  id?: number;
  customer_id: number;
  oil_filter: string;
  oil_filter_2: string;
  oil_nozzle: string;
  oil_nozzle_2: string;
  hot_water_tank: number;
}

interface NozzleParts {
  part1: string;
  part2: string;
  part3: string;
}

// Props
const props = defineProps<{
  existingParts: ServiceParts
  customerId: number
}>()

// Emits
const emit = defineEmits<{
  'close-modal': []
  'save-parts': [parts: Partial<ServiceParts>]
}>()

// Reactive data
const editableParts = ref({} as Partial<ServiceParts>)
const nozzle1 = ref({ part1: '', part2: '', part3: '' } as NozzleParts)
const nozzle2 = ref({ part1: '', part2: '', part3: '' } as NozzleParts)

// ======================================================
// ============== THE UPDATED OIL FILTER LIST ==============
// ======================================================
const oilFilterOptions = ref([
  'RF-1',
  'RF-4',
  '88CR',
  'Big Guy f80-24',
  'Garber Model R',
  'Garber Model M',
  'PurePro f100-10W'
])

const nozzlePart1Options = ref(['a', 'b', 'w'])
const nozzlePart2Options = ref(Array.from({ length: (200 - 45) / 5 + 1 }, (_, i) => (45 + i * 5).toString()))
const nozzlePart3Options = ref(Array.from({ length: (100 - 45) / 5 + 1 }, (_, i) => (45 + i * 5).toString()))

// Watchers
watch(() => props.existingParts, (newVal) => {
  if (!newVal) return;
  // Update the component's internal data when the prop changes
  editableParts.value = { ...newVal, customer_id: props.customerId };
  nozzle1.value = splitNozzle(newVal.oil_nozzle);
  nozzle2.value = splitNozzle(newVal.oil_nozzle_2);
}, { immediate: true, deep: true })

// Functions
// Function to split a combined nozzle string (e.g., "a 55 75") into its parts
const splitNozzle = (nozzleStr: string | undefined): NozzleParts => {
  if (!nozzleStr || typeof nozzleStr !== 'string' || nozzleStr.trim() === '') {
    return { part1: '', part2: '', part3: '' };
  }
  const parts = nozzleStr.split(' ');
  return {
    part1: parts[0] || '',
    part2: parts[1] || '',
    part3: parts[2] || '',
  };
}

// Function to combine nozzle parts into a single string
const combineNozzle = (parts: NozzleParts): string => {
  if (parts.part1 && parts.part2 && parts.part3) {
    return `${parts.part1} ${parts.part2} ${parts.part3}`;
  }
  return ''; // Return empty if any part is missing
}

// Form submission handler
const saveChanges = () => {
  // Before emitting, combine the nozzle parts back into a single string
  editableParts.value.oil_nozzle = combineNozzle(nozzle1.value);
  editableParts.value.oil_nozzle_2 = combineNozzle(nozzle2.value);

  // Emit the save event with the final payload
  emit('save-parts', editableParts.value);
}
</script>```
