<script setup lang="ts">
import { computed, ref, provide, watch, reactive } from 'vue'
import modelSetting from './model-setting.vue'
import { useQuery } from '@pinia/colada'
import {
  ScrollArea,
  InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  Toggle,
  Empty,
  EmptyContent,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
  Button,
} from '@memohai/ui'
import { getProviders } from '@memohai/sdk'
import type { ProvidersGetResponse } from '@memohai/sdk'
import AddProvider from '@/components/add-provider/index.vue'
import ProviderIcon from '@/components/provider-icon/index.vue'
import MasterDetailSidebarLayout from '@/components/master-detail-sidebar-layout/index.vue'

function getInitials(name: string | undefined) {
  const label = name?.trim() ?? ''
  return label ? label.slice(0, 2).toUpperCase() : '?'
}

const { data: providerData } = useQuery({
  key: () => ['providers'],
  query: async () => {
    const { data } = await getProviders({
      throwOnError: true,
    })
    return data
  },
})

const curProvider = ref<ProvidersGetResponse>()
provide('curProvider', curProvider)

const selectProvider = (value: string) => computed(() => {
  return curProvider.value?.name === value
})

const searchText = ref('')
const searchInput = ref('')

const curFilterProvider = computed(() => {
  if (!Array.isArray(providerData.value)) {
    return []
  }
  let list = providerData.value as ProvidersGetResponse[]
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase()
    list = list.filter((p) => (p.name ?? '').toLowerCase().includes(keyword))
  }
  return [...list].sort((a, b) => {
    const ae = a.enable !== false ? 1 : 0
    const be = b.enable !== false ? 1 : 0
    return be - ae
  })
})

watch(curFilterProvider, () => {
  if (curFilterProvider.value.length > 0) {
    curProvider.value = curFilterProvider.value[0]
  } else {
    curProvider.value = { id: '' }
  }
}, {
  immediate: true
})

const openStatus = reactive({
  provideOpen: false
})

</script>

<template>
  <MasterDetailSidebarLayout class="[&_td:last-child]:w-45">
    <template #sidebar-header>
      <InputGroup class="shadow-none">
        <InputGroupInput
          v-model="searchInput"
          :placeholder="$t('models.searchPlaceholder')"
          aria-label="Search models"
        />
        <InputGroupAddon
          align="inline-end"
        >
          <InputGroupButton
            type="button"
            size="icon-xs"
            aria-label="Search models"
            @click="searchText = searchInput"
          >
            <FontAwesomeIcon :icon="['fas', 'magnifying-glass']" />
          </InputGroupButton>
        </InputGroupAddon>
      </InputGroup>
    </template>

    <template
      #sidebar-content
    >
      <SidebarMenu
        v-for="providerItem in curFilterProvider"
        :key="providerItem.name"
      >
        <SidebarMenuItem>
          <SidebarMenuButton
            as-child
            class="justify-start py-5! px-4"
          >
            <Toggle
              :class="[
                'py-4 border',
                curProvider?.name === providerItem.name ? 'border-border' : 'border-transparent',
              ]"
              :model-value="selectProvider(providerItem.name ?? '').value"
              @update:model-value="(isSelect) => {
                if (isSelect) {
                  curProvider = providerItem
                }
              }"
            >
              <span class="relative shrink-0">
                <span class="flex size-7 items-center justify-center rounded-full bg-muted">
                  <ProviderIcon
                    v-if="providerItem.icon"
                    :icon="providerItem.icon"
                    size="1.25em"
                  />
                  <span
                    v-else
                    class="text-xs font-medium text-muted-foreground"
                  >
                    {{ getInitials(providerItem.name) }}
                  </span>
                </span>
                <span
                  v-if="providerItem.enable !== false"
                  class="absolute -bottom-0.5 -right-0.5 size-2.5 rounded-full bg-green-500 ring-2 ring-background"
                />
              </span>
              <span class="truncate">{{ providerItem.name }}</span>
            </Toggle>
          </SidebarMenuButton>
        </SidebarMenuItem>
      </SidebarMenu>
    </template>

    <template #sidebar-footer>
      <AddProvider
        v-model:open="openStatus.provideOpen"
      />
    </template>

    <template #detail>
      <ScrollArea
        v-if="curProvider?.id"
        class="max-h-full h-full"
      >
        <model-setting />
      </ScrollArea>
      <Empty
        v-else
        class="h-full flex justify-center items-center"
      >
        <EmptyHeader>
          <EmptyMedia variant="icon">
            <FontAwesomeIcon :icon="['far', 'rectangle-list']" />
          </EmptyMedia>
        </EmptyHeader>
        <EmptyTitle>{{ $t('provider.emptyTitle') }}</EmptyTitle>
        <EmptyDescription>{{ $t('provider.emptyDescription') }}</EmptyDescription>
        <EmptyContent>
          <Button
            variant="outline"
            @click="openStatus.provideOpen=true"
          >
            {{ $t('provider.addBtn') }}
          </Button>          
        </EmptyContent>
      </Empty>
    </template>
  </MasterDetailSidebarLayout>
</template>    
