<script setup lang="ts">
import { Search, SlidersHorizontal } from "lucide-vue-next";
import Button from "./ui/Button.vue";
import DropdownMenu from "./ui/DropdownMenu.vue";
import DropdownMenuTrigger from "./ui/DropdownMenuTrigger.vue";
import DropdownMenuContent from "./ui/DropdownMenuContent.vue";
import DropdownMenuItem from "./ui/DropdownMenuItem.vue";
import DropdownMenuSeparator from "./ui/DropdownMenuSeparator.vue";
import Popover from "./ui/Popover.vue";
import PopoverTrigger from "./ui/PopoverTrigger.vue";
import PopoverContent from "./ui/PopoverContent.vue";
import Select from "./ui/Select.vue";
import SelectContent from "./ui/SelectContent.vue";
import SelectItem from "./ui/SelectItem.vue";
import SelectTrigger from "./ui/SelectTrigger.vue";
import SelectValue from "./ui/SelectValue.vue";
import { useTranslations } from "../composables/useTranslations";
import type { Column, Filter } from "../types";

const { t } = useTranslations();

const props = defineProps<{
  filters: Filter[];
  allColumns: Column[];
  hiddenColumns: Set<string>;
  searchQuery: string;
  activeFilters: Record<string, string>;
  activeFilterCount: number;
  hasSelection: boolean;
  selectionCount: number;
  canEdit: boolean;
  exportUrl: string;
}>();

const emit = defineEmits<{
  (e: "update:searchQuery", val: string): void;
  (e: "setFilter", key: string, val: string): void;
  (e: "clearFilters"): void;
  (e: "toggleColumn", key: string): void;
  (e: "resetVisibility"): void;
  (e: "openBulkEdit"): void;
  (e: "openBulkDelete"): void;
  (e: "clearSelection"): void;
}>();
</script>

<template>
  <!-- Toolbar -->
  <div class="mb-3 flex flex-wrap items-center gap-2">
    <div class="relative flex items-center">
      <Search
        class="pointer-events-none absolute left-2.5 h-3.5 w-3.5 text-muted-foreground"
      />
      <input
        :value="props.searchQuery"
        type="search"
        :placeholder="t('builder.resources.search') + '…'"
        class="h-8 w-52 rounded-md border border-input bg-background pl-8 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
        @input="
          emit('update:searchQuery', ($event.target as HTMLInputElement).value)
        "
      />
    </div>

    <Popover v-if="props.filters.length > 0">
      <PopoverTrigger as-child>
        <Button variant="outline" size="sm" class="gap-1.5">
          <SlidersHorizontal class="h-3.5 w-3.5" />
          {{ t("builder.resources.filters") }}
          <span
            v-if="props.activeFilterCount > 0"
            class="flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold text-primary-foreground"
          >
            {{ props.activeFilterCount }}
          </span>
        </Button>
      </PopoverTrigger>
      <PopoverContent align="start" class="w-60 p-3">
        <div class="space-y-3">
          <div
            v-for="filter in props.filters"
            :key="filter.key"
            class="space-y-1"
          >
            <label class="text-xs font-medium text-muted-foreground">
              {{ filter.label }}
            </label>
            <Select
              v-if="filter.type === 'select'"
              :model-value="props.activeFilters[filter.key] || '__all__'"
              @update:model-value="
                emit(
                  'setFilter',
                  filter.key,
                  $event === '__all__' ? '' : $event,
                )
              "
            >
              <SelectTrigger class="h-8 w-full">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__all__">
                  {{ t("builder.resources.all") }}
                </SelectItem>
                <SelectItem
                  v-for="(label, val) in filter.options ?? {}"
                  :key="val"
                  :value="String(val)"
                >
                  {{ label }}
                </SelectItem>
              </SelectContent>
            </Select>
            <input
              v-else
              :placeholder="t('builder.resources.all')"
              :value="props.activeFilters[filter.key] ?? ''"
              class="h-8 w-full rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
              @input="
                emit(
                  'setFilter',
                  filter.key,
                  ($event.target as HTMLInputElement).value,
                )
              "
            />
          </div>
          <button
            v-if="props.activeFilterCount > 0"
            class="w-full rounded border border-dashed border-input py-1.5 text-xs text-muted-foreground hover:border-foreground hover:text-foreground"
            @click="emit('clearFilters')"
          >
            {{ t("builder.resources.clear_filters") }}
          </button>
        </div>
      </PopoverContent>
    </Popover>

    <div class="ml-auto flex items-center gap-2">
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button variant="outline" size="sm">
            {{ t("builder.resources.columns") }}
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" class="w-48">
          <DropdownMenuItem
            v-for="col in props.allColumns"
            :key="col.key"
            class="flex items-center gap-2"
            @click.prevent="emit('toggleColumn', col.key)"
          >
            <span class="inline-flex w-4 shrink-0">
              <svg
                v-if="!props.hiddenColumns.has(col.key)"
                class="h-3.5 w-3.5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="3"
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </span>
            {{ col.label }}
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem @click="emit('resetVisibility')">
            {{ t("builder.resources.reset_columns") }}
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button variant="outline" size="sm" class="px-2">
            <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24">
              <circle cx="5" cy="12" r="1.5" />
              <circle cx="12" cy="12" r="1.5" />
              <circle cx="19" cy="12" r="1.5" />
            </svg>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" class="w-40">
          <DropdownMenuItem as-child>
            <a :href="props.exportUrl">
              {{ t("builder.resources.export_csv") }}
            </a>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  </div>

  <!-- Selection row -->
  <div
    v-if="props.hasSelection"
    class="mb-3 flex items-center gap-2 rounded-lg border bg-muted/40 px-4 py-2.5"
  >
    <span class="text-sm font-medium">
      {{ t("builder.resources.selected", { count: props.selectionCount }) }}
    </span>
    <Button
      v-if="props.canEdit"
      size="sm"
      variant="outline"
      @click="emit('openBulkEdit')"
    >
      {{ t("builder.resources.edit") }}
    </Button>
    <Button
      size="sm"
      variant="outline"
      class="border-destructive/30 text-destructive hover:bg-destructive/5 hover:text-destructive"
      @click="emit('openBulkDelete')"
    >
      {{ t("builder.resources.delete") }}
    </Button>
    <Button
      size="sm"
      variant="ghost"
      class="ml-auto text-muted-foreground hover:text-foreground"
      @click="emit('clearSelection')"
    >
      {{ t("builder.resources.clear_selection") }}
    </Button>
  </div>
</template>
