<template>
  <v-dialog v-model="dialog" max-width="760" scrollable>
    <v-card>
      <v-card-title class="tw:flex tw:justify-between tw:items-center tw:gap-2">
        <span class="tw:text-lg tw:font-semibold">{{ title }}</span>
        <v-btn icon="mdi-close" size="small" variant="text" @click="close" />
      </v-card-title>

      <v-divider />

      <v-card-text class="tw:py-4">
        <div class="tw:flex tw:justify-between tw:items-center tw:mb-4 tw:gap-2">
          <v-checkbox
            :model-value="selectAll"
            @update:model-value="toggleSelectAll"
            :label="$t('core.selectAll')"
            hide-details
            density="compact"
          />

          <v-chip color="primary" variant="flat" size="small">
            {{ selectedCount }} / {{ items.length }} {{ $t("core.selected") }}
          </v-chip>
        </div>

        <v-list class="tw:max-h-96 tw:overflow-y-auto tw:border tw:rounded-md tw:py-0">
          <v-list-item
            v-for="item in items"
            :key="item._id"
            @click="toggleSelection(String(item._id))"
            class="tw:cursor-pointer"
          >
            <template #prepend>
              <v-checkbox-btn
                :model-value="selected.includes(String(item._id))"
                @update:model-value="(checked) => setSelection(String(item._id), checked)"
                @click.stop
              />
            </template>

            <v-list-item-title class="tw:text-sm">
              {{ getDisplayValue(item) }}
            </v-list-item-title>
          </v-list-item>
        </v-list>

        <v-alert
          v-if="selectedCount === 0"
          type="warning"
          variant="tonal"
          density="compact"
          class="tw:mt-4"
        >
          {{ $t("core.noItemsSelected") }}
        </v-alert>
      </v-card-text>

      <v-divider />

      <v-card-actions class="tw:px-4 tw:py-3">
        <v-spacer />
        <v-btn variant="text" @click="close">
          {{ $t("core.cancel") }}
        </v-btn>

        <v-btn
          v-if="selectedCount"
          @click="confirm"
          :disabled="selectedCount === 0"
          color="primary"
          variant="flat"
        >
          {{ confirmText }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

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

interface Props {
  modelValue: boolean
  items: any[]
  displayAttribute: string
  title: string
  confirmText: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  "update:modelValue": [value: boolean]
  confirm: [selectedIds: string[]]
}>()

const dialog = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
})

const selected = ref<string[]>([])
const selectAll = ref(false)

const selectedCount = computed(() => selected.value.length)

const getDisplayValue = (item: any) => {
  return item[props.displayAttribute] || item._id
}

const toggleSelection = (id: string) => {
  const index = selected.value.indexOf(id)
  if (index > -1) {
    selected.value.splice(index, 1)
  } else {
    selected.value.push(id)
  }
  updateSelectAllState()
}

const setSelection = (id: string, checked: boolean | null) => {
  const isChecked = Boolean(checked)
  const exists = selected.value.includes(id)
  if (isChecked && !exists) {
    selected.value.push(id)
  } else if (!isChecked && exists) {
    selected.value = selected.value.filter((selectedId) => selectedId !== id)
  }
  updateSelectAllState()
}

const toggleSelectAll = (value: boolean | null) => {
  const enabled = Boolean(value)
  if (enabled) {
    selected.value = props.items.map((item) => String(item._id))
  } else {
    selected.value = []
  }
  selectAll.value = enabled
}

const updateSelectAllState = () => {
  selectAll.value =
    selected.value.length === props.items.length && props.items.length > 0
}

const close = () => {
  dialog.value = false
  selected.value = []
  selectAll.value = false
}

const confirm = () => {
  if (selectedCount.value > 0) {
    emit("confirm", selected.value)
    close()
  }
}

// Initialize selectAll state when items change
watch(
  () => props.items,
  () => {
    updateSelectAllState()
  },
  { immediate: true },
)
</script>
