<!-- src/pages/admin/streets.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">

      <!-- Breadcrumbs -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li>Street Manager</li>
        </ul>
      </div>

      <!-- Page Header -->
      <div class="mt-4 mb-6">
        <h1 class="text-2xl md:text-3xl font-bold flex items-center gap-3">
          <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-info to-info/60 flex items-center justify-center shadow-lg">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5 text-info-content">
              <path stroke-linecap="round" stroke-linejoin="round" d="M9 6.75V15m6-6v8.25m.503 3.498l4.875-2.437c.381-.19.622-.58.622-1.006V4.82c0-.836-.88-1.38-1.628-1.006l-3.869 1.934c-.317.159-.69.159-1.006 0L9.503 3.252a1.125 1.125 0 00-1.006 0L3.622 5.689C3.24 5.88 3 6.27 3 6.695V19.18c0 .836.88 1.38 1.628 1.006l3.869-1.934c.317-.159.69-.159 1.006 0l4.994 2.497c.317.158.69.158 1.006 0z" />
            </svg>
          </div>
          Street Manager
        </h1>
        <p class="text-base-content/60 mt-1 ml-13">Manage street reference data used for address autocomplete. Update re-fetches streets from OpenStreetMap.</p>
      </div>

      <!-- Service unavailable banner -->
      <div v-if="serviceDown" class="alert alert-error mb-4">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
        </svg>
        <span>Address checker service is unavailable. Streets cannot be updated.</span>
      </div>

      <!-- Add Town card -->
      <div class="modern-table-card p-5 mb-4">
        <h2 class="text-sm font-bold uppercase tracking-wide text-base-content/50 mb-3">Add Town</h2>
        <form class="flex flex-wrap gap-3 items-end" @submit.prevent="addTown">
          <div class="form-control">
            <label class="label py-0 mb-1"><span class="label-text text-xs">Town Name</span></label>
            <input
              v-model="newTown"
              type="text"
              placeholder="e.g. Auburn"
              class="input input-bordered input-sm w-48"
              :disabled="isAdding"
            />
          </div>
          <div class="form-control">
            <label class="label py-0 mb-1"><span class="label-text text-xs">State</span></label>
            <select v-model="newState" class="select select-bordered select-sm" :disabled="isAdding">
              <option v-for="s in US_STATES" :key="s" :value="s">{{ s }}</option>
            </select>
          </div>
          <button
            type="submit"
            class="btn btn-sm btn-primary"
            :disabled="!newTown.trim() || isAdding"
          >
            <span v-if="isAdding" class="loading loading-spinner loading-xs"></span>
            <span v-else>Add &amp; Fetch Streets</span>
          </button>
        </form>
      </div>

      <!-- Towns table -->
      <div class="modern-table-card">

        <!-- Loading -->
        <div v-if="isLoading" class="flex justify-center items-center py-16">
          <span class="loading loading-spinner loading-lg text-info"></span>
        </div>

        <!-- Empty -->
        <div v-else-if="towns.length === 0" class="flex flex-col items-center justify-center py-16 text-base-content/50">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-12 h-12 mb-3">
            <path stroke-linecap="round" stroke-linejoin="round" d="M9 6.75V15m6-6v8.25m.503 3.498l4.875-2.437c.381-.19.622-.58.622-1.006V4.82c0-.836-.88-1.38-1.628-1.006l-3.869 1.934c-.317.159-.69.159-1.006 0L9.503 3.252a1.125 1.125 0 00-1.006 0L3.622 5.689C3.24 5.88 3 6.27 3 6.695V19.18c0 .836.88 1.38 1.628 1.006l3.869-1.934c.317-.159.69-.159 1.006 0l4.994 2.497c.317.158.69.158 1.006 0z" />
          </svg>
          <p class="font-medium">No towns yet</p>
          <p class="text-sm mt-1">Add a town above to get started.</p>
        </div>

        <!-- Table -->
        <div v-else class="overflow-x-auto">
          <table class="table table-sm w-full">
            <thead>
              <tr class="text-xs uppercase tracking-wide text-base-content/50">
                <th>Town</th>
                <th>State</th>
                <th class="text-right">Streets</th>
                <th class="text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="town in towns" :key="rowKey(town)" class="hover">

                <!-- Town name — static or inline edit -->
                <td class="font-medium">
                  <template v-if="editingKey === rowKey(town)">
                    <input
                      v-model="editValue"
                      type="text"
                      class="input input-bordered input-xs w-40"
                      @keydown.enter="saveRename(town)"
                      @keydown.escape="cancelEdit"
                      ref="editInput"
                    />
                  </template>
                  <template v-else>
                    {{ town.town }}
                  </template>
                </td>

                <td><span class="badge badge-ghost badge-sm">{{ town.state }}</span></td>

                <td class="text-right font-mono text-sm">{{ town.street_count }}</td>

                <td class="text-right">
                  <div class="flex justify-end gap-1">

                    <!-- Editing mode: Save / Cancel -->
                    <template v-if="editingKey === rowKey(town)">
                      <button
                        class="btn btn-xs btn-success"
                        :disabled="renamingKey === rowKey(town)"
                        @click="saveRename(town)"
                      >
                        <span v-if="renamingKey === rowKey(town)" class="loading loading-spinner loading-xs"></span>
                        <span v-else>Save</span>
                      </button>
                      <button class="btn btn-xs btn-ghost" @click="cancelEdit">Cancel</button>
                    </template>

                    <!-- Normal mode: Edit / Update -->
                    <template v-else>
                      <button
                        class="btn btn-xs btn-ghost"
                        :disabled="updatingKey === rowKey(town)"
                        @click="startEdit(town)"
                        title="Rename town"
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-3 h-3">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125" />
                        </svg>
                      </button>
                      <button
                        class="btn btn-xs btn-info"
                        :disabled="updatingKey === rowKey(town)"
                        @click="updateStreets(town)"
                      >
                        <span v-if="updatingKey === rowKey(town)" class="loading loading-spinner loading-xs"></span>
                        <template v-else>
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-3 h-3 inline mr-1">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                          </svg>
                          Update
                        </template>
                      </button>
                    </template>

                  </div>
                </td>

              </tr>
            </tbody>
          </table>
        </div>

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

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { notify } from '@kyvg/vue3-notification'
import { addressService, TownStreetInfo } from '../../services/addressService'

// ── State ──────────────────────────────────────────────────────────────────

const isLoading   = ref(true)
const serviceDown = ref(false)
const towns       = ref<TownStreetInfo[]>([])

// Add-town form
const newTown  = ref('')
const newState = ref('MA')
const isAdding = ref(false)

// Which row is currently being updated / renamed (null = none)
const updatingKey = ref<string | null>(null)
const editingKey  = ref<string | null>(null)
const renamingKey = ref<string | null>(null)
const editValue   = ref('')
const editInput   = ref<HTMLInputElement | null>(null)

// ── Helpers ────────────────────────────────────────────────────────────────

const rowKey = (t: TownStreetInfo) => `${t.town}|${t.state}`

const US_STATES = [
  'AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN',
  'IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH',
  'NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT',
  'VT','VA','WA','WV','WI','WY',
]

// ── Data loading ───────────────────────────────────────────────────────────

const loadTowns = async () => {
  isLoading.value = true
  try {
    const res = await addressService.listTowns()
    towns.value = res.data.towns
  } catch {
    serviceDown.value = true
  } finally {
    isLoading.value = false
  }
}

// ── Core action: fetch streets for a town (always clears existing first) ───

const fetchStreets = async (town: string, state: string): Promise<number> => {
  const res = await addressService.populateStreets(town, state, true)
  return res.data.streets_added
}

// ── Update existing town ───────────────────────────────────────────────────

const updateStreets = async (town: TownStreetInfo) => {
  updatingKey.value = rowKey(town)
  try {
    const count = await fetchStreets(town.town, town.state)
    const idx = towns.value.findIndex(t => rowKey(t) === rowKey(town))
    if (idx !== -1) towns.value[idx].street_count = count
    notify({ title: 'Streets Updated', text: `${town.town}: ${count} streets.`, type: 'success' })
  } catch (err: any) {
    notify({
      title: 'Update Failed',
      text: err?.response?.data?.detail || `Failed to update ${town.town}.`,
      type: 'error',
    })
  } finally {
    updatingKey.value = null
  }
}

// ── Rename town ────────────────────────────────────────────────────────────

const startEdit = (town: TownStreetInfo) => {
  editingKey.value = rowKey(town)
  editValue.value  = town.town
  nextTick(() => editInput.value?.focus())
}

const cancelEdit = () => {
  editingKey.value = null
  editValue.value  = ''
}

const saveRename = async (town: TownStreetInfo) => {
  const newName = editValue.value.trim()
  if (!newName || newName === town.town) { cancelEdit(); return }

  renamingKey.value = rowKey(town)
  try {
    await addressService.renameTown(town.town, town.state, newName)
    const idx = towns.value.findIndex(t => rowKey(t) === rowKey(town))
    if (idx !== -1) {
      towns.value[idx] = { ...towns.value[idx], town: newName }
      towns.value.sort((a, b) => a.town.localeCompare(b.town))
    }
    notify({ title: 'Town Renamed', text: `'${town.town}' → '${newName}'`, type: 'success' })
    cancelEdit()
  } catch (err: any) {
    notify({
      title: 'Rename Failed',
      text: err?.response?.data?.detail || `Could not rename ${town.town}.`,
      type: 'error',
    })
  } finally {
    renamingKey.value = null
  }
}

// ── Add new town ───────────────────────────────────────────────────────────

const addTown = async () => {
  const town  = newTown.value.trim()
  const state = newState.value
  if (!town) return

  // Prevent duplicates
  if (towns.value.some(t => t.town.toLowerCase() === town.toLowerCase() && t.state === state)) {
    notify({ title: 'Already exists', text: `${town}, ${state} is already in the list.`, type: 'warning' })
    return
  }

  isAdding.value = true
  try {
    const count = await fetchStreets(town, state)
    towns.value.push({ town, state, street_count: count })
    towns.value.sort((a, b) => a.town.localeCompare(b.town))
    notify({ title: 'Town Added', text: `${town}, ${state}: ${count} streets fetched.`, type: 'success' })
    newTown.value = ''
  } catch (err: any) {
    notify({
      title: 'Failed to Add Town',
      text: err?.response?.data?.detail || `Could not fetch streets for ${town}, ${state}.`,
      type: 'error',
    })
  } finally {
    isAdding.value = false
  }
}

onMounted(loadTowns)
</script>
