<!-- src/pages/customer/create.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>Create New Customer</li>
        </ul>
      </div>

      <h1 class="text-3xl font-bold mt-4">
        Create New Customer
      </h1>

      <!-- 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.customer_first_name" type="text" placeholder="First Name" :class="inputClasses(v$.CreateCustomerForm.customer_first_name)" />
                <span v-if="v$.CreateCustomerForm.customer_first_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.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.customer_last_name" type="text" placeholder="Last Name" :class="inputClasses(v$.CreateCustomerForm.customer_last_name)" />
                <span v-if="v$.CreateCustomerForm.customer_last_name.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.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.customer_phone_number" type="tel" placeholder="Phone Number" :class="inputClasses(v$.CreateCustomerForm.customer_phone_number)" @input="acceptNumber()" />
                <span v-if="v$.CreateCustomerForm.customer_phone_number.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.customer_phone_number.$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.customer_home_type" :class="selectClasses(v$.CreateCustomerForm.customer_home_type)">
                  <option disabled :value="-1">Select a type</option>
                  <option v-for="customer in custList" :key="customer.value" :value="customer.value">
                    {{ customer.text }}
                  </option>
                </select>
                 <span v-if="v$.CreateCustomerForm.customer_home_type.$error" class="text-red-500 text-xs mt-1">Required.</span>
              </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.customer_town"
                    type="text"
                    placeholder="Start typing a town name..."
                    :class="inputClasses(v$.CreateCustomerForm.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.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>
                <!-- Quick town buttons -->
                <div class="flex flex-wrap gap-1 mt-2">
                  <button
                    v-for="town in quickTowns"
                    :key="town"
                    type="button"
                    @click="selectQuickTown(town)"
                    :class="['btn', 'btn-xs', CreateCustomerForm.customer_town === town ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']"
                  >{{ town }}</button>
                </div>
                <span v-if="v$.CreateCustomerForm.customer_town.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.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.customer_state" :class="selectClasses(v$.CreateCustomerForm.customer_state)">
                  <option disabled value="">Select a state</option>
                  <option v-for="state in stateList" :key="state.value" :value="state.value">
                    {{ state.text }}
                  </option>
                </select>
                <span v-if="v$.CreateCustomerForm.customer_state.$error" class="text-red-500 text-xs mt-1">Required.</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.customer_address"
                    type="text"
                    placeholder="Start typing your street address..."
                    :class="inputClasses(v$.CreateCustomerForm.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.customer_town && CreateCustomerForm.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.customer_address.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.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.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.customer_zip"
                  type="text"
                  placeholder="Zip Code"
                  :class="[inputClasses(v$.CreateCustomerForm.customer_zip), { 'input-success': zipAutoFilled && !v$.CreateCustomerForm.customer_zip.$error }]"
                />
                <span v-if="v$.CreateCustomerForm.customer_zip.$error" class="text-red-500 text-xs mt-1">
                  {{ v$.CreateCustomerForm.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="form-control">
              <label class="label"><span class="label-text">Description / Notes (Optional)</span></label>
              <textarea v-model="CreateCustomerForm.customer_description" rows="4" placeholder="Description of customer's house, tank, etc." class="textarea textarea-bordered"></textarea>
            </div>
          </div>

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

</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { 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, textareaClasses, validateForm } = useFormValidation();

// Reactive data
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)

const quickTowns = ['Auburn', 'Millbury', 'Sutton', 'Oxford', 'North Oxford', 'Webster',
  'Grafton', 'Dudley', 'Charlton', 'Leicester', 'Cherry Valley', 'Rochdale',
  'Paxton', 'Spencer', 'Worcester']

// 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',
}

// Form object
const CreateCustomerForm = ref({
  customer_last_name: "",
  customer_first_name: "",
  customer_town: "",
  customer_address: "",
  customer_apt: "",
  customer_zip: "",

  customer_phone_number: "",
  customer_description: "",
  customer_home_type: 0,
  customer_state: 0,
})

// 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: {
    customer_last_name: { required, minLength: minLength(1) },
    customer_first_name: { required, minLength: minLength(1) },
    customer_town: { required, minLength: minLength(1) },
    customer_zip: { required, minLength: minLength(5) },

    customer_phone_number: { required },
    customer_home_type: { required },
    customer_state: { required },
    customer_address: { required },
  },
}

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

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

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

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

  // Clear address fields when town changes
  CreateCustomerForm.value.customer_address = ''
  CreateCustomerForm.value.customer_zip = ''
  zipAutoFilled.value = false
}

const selectQuickTown = (townName: string) => {
  CreateCustomerForm.value.customer_town = townName
  CreateCustomerForm.value.customer_state = 0 // MA
  selectedTown.value = { town: townName, state: 'MA', state_id: 0, customer_count: 0 }
  showTownDropdown.value = false
  CreateCustomerForm.value.customer_address = ''
  CreateCustomerForm.value.customer_zip = ''
  zipAutoFilled.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.customer_town.trim()
  if (!townValue) return null

  // Get state abbreviation from state ID using our mapping
  const stateId = CreateCustomerForm.value.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.customer_address.length >= 1) {
    searchStreets(
      townState.town,
      townState.state,
      CreateCustomerForm.value.customer_address
    )
  }
  zipAutoFilled.value = false
}

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

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

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

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

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

const getCustomerTypeList = () => {
  queryService.getCustomerTypes()
    .then((response: any) => { 
        if (response.data && response.data.customer_types) {
             custList.value = response.data.customer_types;
             // Set default to Residential (ID 0) based on user feedback
             if (custList.value.some(t => t.value === 0)) {
                 CreateCustomerForm.value.customer_home_type = 0;
             }
        } else {
            custList.value = [];
        }
    });
}

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

const CreateCustomer = (payload: any) => {
  customerService.create(payload)
    .then((response: any) => {
      if (response.data.ok) {
        const new_user_id = response.data.user.user_id;
        router.push({ name: 'customerProfile', params: { id: new_user_id } });
      } else {
        notify({ title: "Error", text: response.data.error || "Failed to create customer.", type: "error" });
      }
    });
}

const onSubmit = () => {
  v$.value.$validate(); // Trigger validation
  if (!v$.value.$error) {
    // If validation passes, submit the form
    CreateCustomer(CreateCustomerForm.value);
  } else {
    // If validation fails, show a single notification
    notify({ title: "Validation Error", text: "Please fill out all required fields correctly.", type: "error" });
    console.log("Form validation failed.");
  }
}

// Lifecycle
onMounted(() => {
  userStatus();
  getCustomerTypeList();
  getStatesList();
})
</script>
