<script setup lang="ts">
import { computed } from "vue";
import { Check, Settings2 } from "lucide-vue-next";
import Button from "../components/ui/Button.vue";
import DropdownMenu from "../components/ui/DropdownMenu.vue";
import DropdownMenuTrigger from "../components/ui/DropdownMenuTrigger.vue";
import DropdownMenuContent from "../components/ui/DropdownMenuContent.vue";
import DropdownMenuLabel from "../components/ui/DropdownMenuLabel.vue";
import DropdownMenuSeparator from "../components/ui/DropdownMenuSeparator.vue";
import DropdownMenuItem from "../components/ui/DropdownMenuItem.vue";
import PageHeader from "../components/PageHeader.vue";
import WidgetRenderer from "../components/WidgetRenderer.vue";
import { useTranslations } from "../composables/useTranslations";
import { useWidgetManager } from "../composables/useWidgetManager";

const { t } = useTranslations();

type WidgetDefinition = {
  key: string;
  label: string;
  component: string;
  width: "full" | "half" | "third";
  data: Record<string, unknown>;
  permission: string | null;
  hideable: boolean;
};

const props = defineProps<{
  widgets: WidgetDefinition[];
  hiddenWidgetKeys: string[];
}>();

const { hiddenKeys, hideableWidgets, toggleWidget, hideWidget } =
  useWidgetManager(props.hiddenWidgetKeys);

const hideableWidgetList = computed(() => hideableWidgets(props.widgets));
</script>

<template>
  <PageHeader :title="t('builder.nav.dashboard')">
    <template v-if="hideableWidgetList.length > 0" #actions>
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button variant="outline" size="sm">
            <Settings2 class="mr-2 h-4 w-4" />
            {{ t("builder.dashboard.manage_widgets") }}
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" class="min-w-52">
          <DropdownMenuLabel>
            {{ t("builder.dashboard.widgets") }}
          </DropdownMenuLabel>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            v-for="w in hideableWidgetList"
            :key="w.key"
            class="justify-between"
            @click="toggleWidget(w.key)"
          >
            <span>{{ w.label }}</span>
            <Check
              v-if="!hiddenKeys.includes(w.key)"
              class="h-4 w-4 text-primary"
            />
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </template>
  </PageHeader>

  <WidgetRenderer
    :widgets="widgets"
    :hidden-widget-keys="hiddenKeys"
    @hide="hideWidget"
  />
</template>
