<script setup>
import MainNav from "~/components/MainNav.vue";
import dayjs from "dayjs";
import GlobalMessages from "~/components/GlobalMessages.vue";
import TenantDropdown from "~/components/TenantDropdown.vue";
import LabelPrinterButton from "~/components/LabelPrinterButton.vue";
import {useCalculatorStore} from '~/stores/calculator'
import SessionRefreshModal from "~/components/SessionRefreshModal.vue";

const dataStore = useDataStore()
const colorMode = useColorMode()
const {isHelpSlideoverOpen} = useDashboard()
const router = useRouter()
const route = useRoute()

const auth = useAuthStore()
const labelPrinter = useLabelPrinterStore()
const calculatorStore = useCalculatorStore()
const { hasUnread, refresh: refreshChangelog } = useChangelog()

const month = dayjs().format("MM")

const actions = [
  {
    id: 'new-customer',
    label: 'Kunde hinzufügen',
    icon: 'i-heroicons-user-group',
    to: "/customers/create",
  },
  {
    id: 'new-vendor',
    label: 'Lieferant hinzufügen',
    icon: 'i-heroicons-truck',
    to: "/vendors/create",
  },
  {
    id: 'new-contact',
    label: 'Ansprechpartner hinzufügen',
    icon: 'i-heroicons-user-group',
    to: "/contacts/create",
  },
  {
    id: 'new-task',
    label: 'Aufgabe hinzufügen',
    icon: 'i-heroicons-rectangle-stack',
    to: "/tasks/create",
  },
  {
    id: 'new-plant',
    label: 'Objekt hinzufügen',
    icon: 'i-heroicons-clipboard-document',
    to: "/plants/create",
  },
  {
    id: 'new-product',
    label: 'Artikel hinzufügen',
    icon: 'i-heroicons-puzzle-piece',
    to: "/products/create",
  },
  {
    id: 'new-project',
    label: 'Projekt hinzufügen',
    icon: 'i-heroicons-clipboard-document-check',
    to: "/projects/create",
  }
]

const groups = computed(() => [
  {
    key: 'actions',
    commands: actions
  }, {
    key: "customers",
    label: "Kunden",
    commands: dataStore.customers.map(item => {
      return {id: item.id, label: item.name, to: `/customers/show/${item.id}`}
    })
  }, {
    key: "vendors",
    label: "Lieferanten",
    commands: dataStore.vendors.map(item => {
      return {id: item.id, label: item.name, to: `/vendors/show/${item.id}`}
    })
  }, {
    key: "contacts",
    label: "Ansprechpartner",
    commands: dataStore.contacts.map(item => {
      return {id: item.id, label: item.fullName, to: `/contacts/show/${item.id}`}
    })
  }, {
    key: "products",
    label: "Artikel",
    commands: dataStore.products.map(item => {
      return {id: item.id, label: item.name, to: `/products/show/${item.id}`}
    })
  }, {
    key: "tasks",
    label: "Aufgaben",
    commands: dataStore.tasks.map(item => {
      return {id: item.id, label: item.name, to: `/tasks/show/${item.id}`}
    })
  }, {
    key: "plants",
    label: "Objekte",
    commands: dataStore.plants.map(item => {
      return {id: item.id, label: item.name, to: `/plants/show/${item.id}`}
    })
  }, {
    key: "projects",
    label: "Projekte",
    commands: dataStore.projects.map(item => {
      return {id: item.id, label: item.name, to: `/projects/show/${item.id}`}
    })
  }
].filter(Boolean))

// --- Footer Links nutzen jetzt den zentralen Calculator Store ---
const footerItems = computed(() => [
  {
    label: 'Taschenrechner',
    icon: 'i-heroicons-calculator',
    click: () => calculatorStore.toggle()
  },
  {
    label: 'Hilfe & Info',
    icon: 'i-heroicons-question-mark-circle',
    badge: hasUnread.value ? 'Neu' : null,
    click: () => isHelpSlideoverOpen.value = true
  }
])

onMounted(() => {
  void refreshChangelog()
})

</script>

<template>
  <div v-if="!auth.loading">
    <SessionRefreshModal />
    <div v-if="auth.activeTenantData?.locked === 'maintenance_tenant'">
      <UContainer class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <UCard class="max-w-lg text-center p-10">
          <UColorModeImage
              light="/Logo_Hell_Weihnachten.png"
              dark="/Logo_Dunkel_Weihnachten.png"
              class=" mx-auto my-10"
              v-if="month === '12'"
          />
          <UColorModeImage
              light="/Logo.png"
              dark="/Logo_Dark.png"
              class="mx-auto my-10"
              v-else
          />
          <div class="flex justify-center mb-6">
            <UIcon name="i-heroicons-exclamation-triangle-solid" class="w-16 h-16 text-yellow-500"/>
          </div>

          <h1 class="text-2xl font-bold text-gray-900 dark:text-white mb-4">
            Wartungsarbeiten
          </h1>
          <p class="text-gray-600 dark:text-gray-300 mb-8">
            Dieser FEDEO Mandant wird derzeit gewartet. Bitte versuche es in einigen Minuten erneut oder verwende einen
            anderen Mandanten.
          </p>
          <div class="mx-auto text-left flex flex-row justify-between my-3" v-for="tenant in auth.tenants">
            {{ tenant.name }}
            <UButton
                :disabled="tenant.locked"
                @click="auth.switchTenant(tenant.id)"
            >Wählen
            </UButton>
          </div>
        </UCard>
      </UContainer>
    </div>
    <div v-else-if="auth.activeTenantData?.locked === 'maintenance'">
      <UContainer class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <UCard class="max-w-lg text-center p-10">
          <UColorModeImage
              light="/Logo_Hell_Weihnachten.png"
              dark="/Logo_Dunkel_Weihnachten.png"
              class=" mx-auto my-10"
              v-if="month === '12'"
          />
          <UColorModeImage
              light="/Logo.png"
              dark="/Logo_Dark.png"
              class="mx-auto my-10"
              v-else
          />
          <div class="flex justify-center mb-6">
            <UIcon name="i-heroicons-exclamation-triangle-solid" class="w-16 h-16 text-yellow-500"/>
          </div>

          <h1 class="text-2xl font-bold text-gray-900 dark:text-white mb-4">
            Wartungsarbeiten
          </h1>
          <p class="text-gray-600 dark:text-gray-300 mb-8">
            FEDEO wird derzeit gewartet. Bitte versuche es in einigen Minuten erneut.
          </p>
        </UCard>
      </UContainer>
    </div>
    <div v-else-if="auth.activeTenantData?.locked === 'no_subscription'">
      <UContainer class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <UCard class="max-w-lg text-center p-10">
          <UColorModeImage
              light="/Logo_Hell_Weihnachten.png"
              dark="/Logo_Dunkel_Weihnachten.png"
              class=" mx-auto my-10"
              v-if="month === '12'"
          />
          <UColorModeImage
              light="/Logo.png"
              dark="/Logo_Dark.png"
              class="mx-auto my-10"
              v-else
          />
          <div class="flex justify-center mb-6">
            <UIcon name="i-heroicons-credit-card" class="w-16 h-16 text-red-600"/>
          </div>

          <h1 class="text-2xl font-bold text-gray-900 dark:text-white mb-4">
            Kein Aktives Abonnement für diesen Mandant.
          </h1>
          <p class="text-gray-600 dark:text-gray-300 mb-8">
            Bitte wenden Sie sich an den FEDEO Support um ein Abonnement zu erhalten oder verwenden Sie einen anderen
            Mandanten.
          </p>
          <div class="mx-auto text-left flex flex-row justify-between my-3" v-for="tenant in auth.tenants">
            {{ tenant.name }}
            <UButton
                :disabled="tenant.locked"
                @click="auth.switchTenant(tenant.id)"
            >Wählen
            </UButton>
          </div>
        </UCard>
      </UContainer>
    </div>
    <div class="safearea flex min-h-screen w-full flex-col overflow-hidden" v-else>
<!--      <div
          class="border-b border-default bg-default px-3 py-2"
          style="padding-top: max(env(safe-area-inset-top, 0px), 0.5rem);"
      >
        <TenantDropdown class="min-w-0 w-full max-w-sm" />
      </div>-->

      <UDashboardGroup class="flex min-h-0 flex-1 overflow-hidden">


        <UDashboardSidebar
            id="sidebar"
            collapsible
            resizable
            :default-size="18"
            :min-size="14"
            :max-size="24"
            class="shrink-0 border-r border-default bg-default"
        >
          <template #header>
            <TenantDropdown class="w-full"/>

          </template>

          <template #default="{ collapsed }">
            <MainNav :collapsed="collapsed" />
          </template>

          <template #footer="{ collapsed }">
            <div class="flex flex-col gap-3 w-full">
              <div class="flex items-center gap-2">
                <UColorModeSwitch :class="[collapsed ? 'mx-auto' : 'ml-3']"/>
                <UDashboardSidebarCollapse v-if="collapsed" class="mx-auto" />
              </div>

              <LabelPrinterButton class="w-full"/>

              <div class="flex flex-col gap-1">
                <UButton
                    v-for="item in footerItems"
                    :key="item.label"
                    color="gray"
                    variant="ghost"
                    class="w-full min-w-0 justify-start rounded-lg px-2.5 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-800"
                    :icon="item.icon"
                    @click="item.click ? item.click() : null"
                >
                  <span v-if="!collapsed">{{ item.label }}</span>

                  <template #trailing>
                    <UBadge v-if="!collapsed && item.badge" color="primary" variant="solid" size="xs">
                      {{ item.badge }}
                    </UBadge>
                  </template>
                </UButton>
              </div>

              <USeparator class="sticky bottom-0 w-full"/>
              <UserDropdown style="margin-bottom: env(safe-area-inset-bottom, 10px) !important;" class="w-full"/>
            </div>
          </template>
        </UDashboardSidebar>


        <UDashboardPanel class="flex min-w-0 flex-1 flex-col overflow-hidden">
          <slot/>

        </UDashboardPanel>
      </UDashboardGroup>

      <TelephonyCallOverlay/>
      <HelpSlideover/>

      <Calculator v-if="calculatorStore.isOpen"/>
    </div>
  </div>

  <div
      v-else
      class="flex flex-col"
  >
    <UColorModeImage
        light="/Logo_Hell_Weihnachten.png"
        dark="/Logo_Dunkel_Weihnachten.png"
        class="w-1/3 mx-auto my-10"
        v-if="month === '12'"
    />
    <UColorModeImage
        light="/Logo.png"
        dark="/Logo_Dark.png"
        class="w-1/3 mx-auto my-10"
        v-else
    />

    <div v-if="!auth.activeTenant" class="w-1/2 mx-auto text-center">
      <h3 class="text-center font-bold text-2xl mb-5">Kein Aktiver Mandant. Bitte wählen Sie ein Mandant.</h3>
      <div class="mx-auto w-1/2 flex flex-row justify-between my-3" v-for="tenant in auth.tenants">
        <span class="text-left">{{ tenant.name }}</span>
        <UButton
            @click="auth.switchTenant(tenant.id)"
        >Wählen
        </UButton>
      </div>
      <UButton
          variant="outline"
          color="error"
          @click="auth.logout()"
      >Abmelden
      </UButton>
    </div>
    <div v-else>
      <UProgress animation="carousel" class="w-3/4 mx-auto mt-10"/>
    </div>

  </div>

</template>
