<!-- src/pages/customer/edit.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.id">
            <router-link :to="{ name: 'customerProfile', params: { id: customer.id } }">
              {{ customer.customer_first_name }} {{ customer.customer_last_name }}
            </router-link>
          </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">
          Edit Customer: {{ customer.account_number }}
        </h1>
        <router-link :to="{ name: 'customerProfile', params: { id: customer.id } }" class="btn btn-secondary btn-sm mt-2 sm:mt-0">
          View 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">

          <!-- SECTION 1: General Info -->
          <div>
            <h2 class="text-lg font-bold">General Info</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <!-- First Name -->
              <div class="form-control">
                <label class="label"><span class="label-text">First Name</span></label>
                <input v-model="CreateCustomerForm.basicInfo.customer_first_name" type="text" placeholder="First Name" :class="inputClasses(v$.CreateCustomerForm.basicInfo.customer_first_name)" />
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_first_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_first_name.$errors[0].$message }}
                </span>
              </div>
              <!-- Last Name -->
              <div class="form-control">
                <label class="label"><span class="label-text">Last Name</span></label>
                <input v-model="CreateCustomerForm.basicInfo.customer_last_name" type="text" placeholder="Last Name" :class="inputClasses(v$.CreateCustomerForm.basicInfo.customer_last_name)" />
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_last_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_last_name.$errors[0].$message }}
                </span>
              </div>
              <!-- Phone Number -->
              <div class="form-control">
                <label class="label"><span class="label-text">Phone Number</span></label>
                <input v-model="CreateCustomerForm.basicInfo.customer_phone_number" type="text" placeholder="Phone Number" :class="inputClasses(v$.CreateCustomerForm.basicInfo.customer_phone_number)" @input="acceptNumber()" />
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_phone_number.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_phone_number.$errors[0].$message }}
                </span>
              </div>
              <!-- Email -->
              <div class="form-control">
                <label class="label"><span class="label-text">Email (Optional)</span></label>
                <input v-model="CreateCustomerForm.basicInfo.customer_email" type="text" placeholder="Email" :class="inputClasses(v$.CreateCustomerForm.basicInfo.customer_email)" />
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_email.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_email.$errors[0].$message }}
                </span>
              </div>
              <!-- Customer Type -->
              <div class="form-control">
                <label class="label"><span class="label-text">Customer Type</span></label>
                <select v-model="CreateCustomerForm.basicInfo.customer_home_type" :class="selectClasses(v$.CreateCustomerForm.basicInfo.customer_home_type)">
                  <option v-for="customer in custList" :key="customer.value" :value="customer.value">
                    {{ customer.text }}
                  </option>
                </select>
              </div>
            </div>
          </div>

          <!-- SECTION 2: Address -->
          <div>
            <h2 class="text-lg font-bold">Address</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- Town with Autocomplete -->
              <div class="form-control relative">
                <label class="label"><span class="label-text">Town</span></label>
                <div class="relative">
                  <input
                    v-model="CreateCustomerForm.basicInfo.customer_town"
                    type="text"
                    placeholder="Start typing a town name..."
                    :class="inputClasses(v$.CreateCustomerForm.basicInfo.customer_town)"
                    autocomplete="off"
                    @input="onTownInput"
                    @keydown="(e) => handleTownKeydown(e, selectTown)"
                    @blur="closeTownDropdown"
                    @focus="onTownFocus"
                  />
                  <!-- Loading indicator -->
                  <span v-if="isLoadingTowns" class="absolute right-3 top-1/2 -translate-y-1/2">
                    <span class="loading loading-spinner loading-xs"></span>
                  </span>
                </div>
                <!-- Town Suggestions Dropdown -->
                <div
                  v-if="showTownDropdown && townSuggestions.length > 0"
                  class="absolute z-50 top-full left-0 right-0 mt-1 bg-base-100 border border-base-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
                >
                  <div
                    v-for="(suggestion, index) in townSuggestions"
                    :key="`${suggestion.town}-${suggestion.state}`"
                    class="px-3 py-2 cursor-pointer hover:bg-base-200 transition-colors"
                    :class="{ 'bg-base-200': index === highlightedTownIndex }"
                    @mousedown.prevent="selectTown(suggestion)"
                  >
                    <div class="font-medium">{{ suggestion.town }}</div>
                    <div class="text-xs text-base-content/60">
                      {{ suggestion.state }}
                      <span class="badge badge-xs badge-ghost ml-1">{{ suggestion.customer_count }} customers</span>
                    </div>
                  </div>
                </div>
                <!-- No results message -->
                <div
                  v-if="showTownDropdown && townSuggestions.length === 0 && !isLoadingTowns && CreateCustomerForm.basicInfo.customer_town.length >= 2"
                  class="absolute z-50 top-full left-0 right-0 mt-1 bg-base-100 border border-base-300 rounded-lg shadow-lg p-3 text-sm text-base-content/60"
                >
                  No matching towns found. You can enter a new town name.
                </div>
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_town.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_town.$errors[0].$message }}
                </span>
              </div>

              <!-- State -->
              <div class="form-control">
                <label class="label"><span class="label-text">State</span></label>
                <select v-model="CreateCustomerForm.basicInfo.customer_state" :class="selectClasses(v$.CreateCustomerForm.basicInfo.customer_state)">
                  <option v-for="state in stateList" :key="state.value" :value="state.value">
                    {{ state.text }}
                  </option>
                </select>
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_state.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_state.$errors[0].$message }}
                </span>
              </div>

              <!-- Street Address with Autocomplete -->
              <div class="form-control relative">
                <label class="label"><span class="label-text">Street Address</span></label>
                <div class="relative">
                  <input
                    v-model="CreateCustomerForm.basicInfo.customer_address"
                    type="text"
                    placeholder="Start typing your street address..."
                    :class="inputClasses(v$.CreateCustomerForm.basicInfo.customer_address)"
                    autocomplete="off"
                    @input="onAddressInput"
                    @keydown="(e) => handleStreetKeydown(e, selectStreet)"
                    @blur="closeStreetDropdown"
                    @focus="onAddressFocus"
                  />
                  <!-- Loading indicator -->
                  <span v-if="isLoadingStreets" class="absolute right-3 top-1/2 -translate-y-1/2">
                    <span class="loading loading-spinner loading-xs"></span>
                  </span>
                </div>
                <!-- Street Suggestions Dropdown -->
                <div
                  v-if="showStreetDropdown && streetSuggestions.length > 0"
                  class="absolute z-50 top-full left-0 right-0 mt-1 bg-base-100 border border-base-300 rounded-lg shadow-lg max-h-60 overflow-y-auto"
                >
                  <div
                    v-for="(suggestion, index) in streetSuggestions"
                    :key="suggestion.street_name + index"
                    class="px-3 py-2 cursor-pointer hover:bg-base-200 transition-colors"
                    :class="{ 'bg-base-200': index === highlightedStreetIndex }"
                    @mousedown.prevent="selectStreet(suggestion)"
                  >
                    <div class="font-medium">{{ suggestion.street_name }}</div>
                    <div class="text-xs text-base-content/60">
                      {{ suggestion.full_address }}
                      <span v-if="suggestion.zip" class="badge badge-xs badge-primary ml-1">{{ suggestion.zip }}</span>
                    </div>
                  </div>
                </div>
                <!-- Helper text -->
                <p v-if="!CreateCustomerForm.basicInfo.customer_town && CreateCustomerForm.basicInfo.customer_address.length > 0" class="text-xs text-base-content/60 mt-1">
                  Enter a town first for address suggestions
                </p>
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_address.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_address.$errors[0].$message }}
                </span>
              </div>

              <!-- Apt, Suite, etc. -->
              <div class="form-control">
                <label class="label"><span class="label-text">Apt, Suite, etc. (Optional)</span></label>
                <input v-model="CreateCustomerForm.basicInfo.customer_apt" type="text" placeholder="Apt, suite, unit..." class="input input-bordered input-sm w-full" />
              </div>

              <!-- Zip Code (Auto-populated) -->
              <div class="form-control">
                <label class="label">
                  <span class="label-text">Zip Code</span>
                  <span v-if="zipAutoFilled" class="label-text-alt text-success">Auto-filled</span>
                </label>
                <input
                  v-model="CreateCustomerForm.basicInfo.customer_zip"
                  type="text"
                  placeholder="Zip Code"
                  :class="[inputClasses(v$.CreateCustomerForm.basicInfo.customer_zip), { 'input-success': zipAutoFilled && !v$.CreateCustomerForm.basicInfo.customer_zip.$error }]"
                />
                <span v-if="v$.CreateCustomerForm.basicInfo.customer_zip.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.basicInfo.customer_zip.$errors[0].$message }}
                </span>
              </div>
            </div>
          </div>

          <!-- SECTION 3: Delivery Details -->
          <div>
            <h2 class="text-lg font-bold">Delivery Details</h2>
            <div class="divider mt-2 mb-4"></div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- Fill Location -->
              <div class="form-control">
                <label class="label"><span class="label-text">Fill Location</span></label>
                <input v-model="CreateCustomerForm.basicInfo.customer_fill_location" type="text" placeholder="0-12" class="input input-bordered input-sm w-full" />
              </div>
              <!-- Description -->
              <div class="form-control md:col-span-2">
                <label class="label"><span class="label-text">Description / Notes</span></label>
                <textarea v-model="CreateCustomerForm.basicInfo.customer_description" rows="4" placeholder="Description of customer's house, tank, etc." class="textarea textarea-bordered"></textarea>
              </div>
            </div>
          </div>



          <!-- SUBMIT BUTTON -->
          <div class="pt-4">
            <button type="submit" class="btn btn-primary btn-sm">Save Changes</button>
          </div>
        </form>
      </div>
    </div>
  </div>




</template>



<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { authService } from '../../services/authService'
import { customerService } from '../../services/customerService'
import { queryService } from '../../services/queryService'
import { StateOption, HomeTypeOption } from '../../types/models'
import { useTownAutocomplete, useStreetAutocomplete } from '../../composables/useAddressAutocomplete'
import { useFormValidation } from '../../composables/useFormValidation'
import { TownSuggestion, StreetSuggestion } from '../../services/addressService'
import useValidate from "@vuelidate/core";
import { email, minLength, required } from "@vuelidate/validators";
import { notify } from "@kyvg/vue3-notification";

const { inputClasses, selectClasses, validateForm } = useFormValidation();

// Reactive data
const route = useRoute()
const router = useRouter()
const user = ref(null)
const stateList = ref<StateOption[]>([])
const custList = ref<HomeTypeOption[]>([])

// Track selected town for street autocomplete
const selectedTown = ref<TownSuggestion | null>(null)
const zipAutoFilled = ref(false)

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

const customer = ref({
  id: 0,
  user_id: 0,
  customer_first_name: '',
  customer_last_name: '',
  customer_town: '',
  customer_state: 0,
  customer_zip: '',
  customer_apt: '',
  customer_address: '',
  customer_home_type: 0,
  customer_phone_number: '',
  account_number: '',
})
const customerDescription = ref({
  id: 0,
  customer_id: 0,
  account_number: '',
  company_id: '',
  fill_location: 0,
  description: '',
})
const CreateCustomerForm = ref({
  basicInfo: {
    customer_last_name: "",
    customer_first_name: "",
    customer_town: "",
    customer_apt: "",
    customer_home_type: 0,
    customer_zip: "",
    customer_automatic: false,
    customer_email: "",
    customer_phone_number: "",
    customer_state: 0,
    customer_address: "",
    customer_description: "",
    customer_fill_location: 0,
  },
  servicePlan: {
    contract_plan: 0,
    contract_years: 1,
    contract_start_date: "",
  },
})
const renewalDate = ref("")

// Autocomplete composables
const {
  townSuggestions,
  isLoadingTowns,
  showTownDropdown,
  highlightedTownIndex,
  searchTowns,
  closeTownDropdown,
  handleTownKeydown,
} = useTownAutocomplete()

const {
  streetSuggestions,
  isLoadingStreets,
  showStreetDropdown,
  highlightedStreetIndex,
  searchStreets,
  closeStreetDropdown,
  handleStreetKeydown,
} = useStreetAutocomplete()

// Validation rules
const rules = {
  CreateCustomerForm: {
    basicInfo: {
      customer_last_name: { required, minLength: minLength(1) },
      customer_first_name: { required, minLength: minLength(1) },
      customer_town: { required, minLength: minLength(1) },
      customer_home_type: { required },
      customer_zip: { required, minLength: minLength(5) },
      customer_email: { email },
      customer_phone_number: { required },
      customer_state: { required },
      customer_address: { required },
    },
  },
}

// Vuelidate instance
const v$ = useValidate(rules, { CreateCustomerForm })

// Town autocomplete handlers
const onTownInput = () => {
  searchTowns(CreateCustomerForm.value.basicInfo.customer_town)
  // Clear selected town when user types (they're changing it)
  selectedTown.value = null
}

const onTownFocus = () => {
  if (CreateCustomerForm.value.basicInfo.customer_town.length >= 2) {
    searchTowns(CreateCustomerForm.value.basicInfo.customer_town)
  }
}

const selectTown = (suggestion: TownSuggestion) => {
  CreateCustomerForm.value.basicInfo.customer_town = suggestion.town
  CreateCustomerForm.value.basicInfo.customer_state = suggestion.state_id
  selectedTown.value = suggestion
  showTownDropdown.value = false
}

// Helper to get current town and state for street search
const getCurrentTownState = () => {
  // If a town was selected from dropdown, use that
  if (selectedTown.value) {
    return { town: selectedTown.value.town, state: selectedTown.value.state }
  }

  // Otherwise, use whatever is typed in the town field
  const townValue = CreateCustomerForm.value.basicInfo.customer_town.trim()
  if (!townValue) return null

  // Get state abbreviation from state ID using our mapping
  const stateId = CreateCustomerForm.value.basicInfo.customer_state
  const stateAbbr = STATE_ABBR_MAP[stateId] || 'MA'

  return { town: townValue, state: stateAbbr }
}

// Address autocomplete handlers
const onAddressInput = () => {
  const townState = getCurrentTownState()
  if (townState && CreateCustomerForm.value.basicInfo.customer_address.length >= 1) {
    searchStreets(
      townState.town,
      townState.state,
      CreateCustomerForm.value.basicInfo.customer_address
    )
  }
  zipAutoFilled.value = false
}

const onAddressFocus = () => {
  const townState = getCurrentTownState()
  if (townState && CreateCustomerForm.value.basicInfo.customer_address.length >= 1) {
    searchStreets(
      townState.town,
      townState.state,
      CreateCustomerForm.value.basicInfo.customer_address
    )
  }
}

const selectStreet = (suggestion: StreetSuggestion) => {
  CreateCustomerForm.value.basicInfo.customer_address = suggestion.street_name
  if (suggestion.zip) {
    CreateCustomerForm.value.basicInfo.customer_zip = suggestion.zip
    zipAutoFilled.value = true
    // Flash effect for auto-filled zip
    setTimeout(() => {
      zipAutoFilled.value = false
    }, 2000)
  }
  showStreetDropdown.value = false
}

// Watch for manual state changes to update selectedTown
watch(() => CreateCustomerForm.value.basicInfo.customer_state, (newState) => {
  if (newState && CreateCustomerForm.value.basicInfo.customer_town) {
    // Find the state abbreviation
    const stateOption = stateList.value.find(s => s.value === newState)
    if (stateOption) {
      selectedTown.value = {
        town: CreateCustomerForm.value.basicInfo.customer_town,
        state: stateOption.text.split(' - ')[0] || stateOption.text,
        state_id: newState,
        customer_count: 0
      }
    }
  }
})

// Functions
const acceptNumber = () => {
  let x = CreateCustomerForm.value.basicInfo.customer_phone_number.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  if (x) {
    CreateCustomerForm.value.basicInfo.customer_phone_number = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
  } else {
    CreateCustomerForm.value.basicInfo.customer_phone_number = '';
  }
}

const userStatus = () => {
  authService.whoami()
    .then((response: any) => {
      if (response.data.ok) {
        user.value = response.data.user;
      }
    })
    .catch(() => {
      user.value = null
    })
}

const getCustomerDescription = (userid: number) => {
  customerService.getDescription(userid).then((response: any) => {
    customerDescription.value = response.data
    CreateCustomerForm.value.basicInfo.customer_description = customerDescription.value.description;
    CreateCustomerForm.value.basicInfo.customer_fill_location = customerDescription.value.fill_location
  })
}

const getCustomer = (userid: number) => {
  customerService.getById(userid)
    .then((response: any) => {
      const data = response.data?.customer || response.data;
      if (data) {
        customer.value = data;
        getCustomerDescription(customer.value.id);
        CreateCustomerForm.value.basicInfo.customer_last_name = data.customer_last_name;
        CreateCustomerForm.value.basicInfo.customer_first_name = data.customer_first_name;
        CreateCustomerForm.value.basicInfo.customer_town = data.customer_town;
        CreateCustomerForm.value.basicInfo.customer_state = data.customer_state;
        CreateCustomerForm.value.basicInfo.customer_zip = data.customer_zip;
        CreateCustomerForm.value.basicInfo.customer_phone_number = data.customer_phone_number;
        CreateCustomerForm.value.basicInfo.customer_home_type = data.customer_home_type;
        CreateCustomerForm.value.basicInfo.customer_apt = data.customer_apt;
        CreateCustomerForm.value.basicInfo.customer_email = data.customer_email;
        CreateCustomerForm.value.basicInfo.customer_address = data.customer_address;

        if (data.customer_automatic === 1) {
          CreateCustomerForm.value.basicInfo.customer_automatic = true
        }
        if (data.customer_automatic === 0) {
          CreateCustomerForm.value.basicInfo.customer_automatic = false
        }

        // Initialize selectedTown for existing customer data
        if (data.customer_town && data.customer_state) {
          const stateOption = stateList.value.find(s => s.value === data.customer_state)
          if (stateOption) {
            selectedTown.value = {
              town: data.customer_town,
              state: stateOption.text.split(' - ')[0] || stateOption.text,
              state_id: data.customer_state,
              customer_count: 0
            }
          }
        }
      }
    })
}

const editItem = (payload: any) => {
  customerService.update(customer.value.id, payload)
    .then((response: any) => {
      if (response.data.ok) {
        router.push({ name: "customerProfile", params: { id: customer.value.id }, query: { success: 'true' } });
      } else if (response.data.error) {
        router.push("/");
      }
    })
}

const onSubmit = async () => {
  const isValid = await validateForm(v$);
  if (!isValid) return;

  const payload = {
    ...CreateCustomerForm.value.basicInfo,
    service_plan: CreateCustomerForm.value.servicePlan
  };
  editItem(payload);
}

const getCustomerTypeList = () => {
  queryService.getCustomerTypes()
    .then((response: any) => {
      custList.value = response.data?.customer_types || [];
    });
}

const getStatesList = () => {
  queryService.getStates()
    .then((response: any) => {
      stateList.value = response.data?.states || [];
    });
}

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 renewContract = () => {
  if (!renewalDate.value) {
    alert('Please select a renewal date');
    return;
  }
  CreateCustomerForm.value.servicePlan.contract_years += 1;
  CreateCustomerForm.value.servicePlan.contract_start_date = renewalDate.value;
  renewalDate.value = '';
  alert('Contract renewed! Years increased by 1 and start date updated.');
}

// Lifecycle
onMounted(async () => {
  userStatus()
  // Load states first so we can initialize selectedTown properly
  await getStatesList();
  await getCustomerTypeList();
  getCustomer(route.params.id)
})
</script>
