<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useAgentCatalogStore } from '@/store/agentCatalogStore'
import { useUserStore } from '@/store/userStore'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Alert, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { useRouter } from 'vue-router'
import { AGENTS_LIBRARY_TEST_IDS } from './agents-library-testids'
import { storeToRefs } from 'pinia'
import AgentCard from './AgentCard.vue'
import { usePrefStore } from '@/store/prefStore'
import { UserProfileLabelMapper } from '@/constants/user'
import { WT1iser } from '@/lib/wt1'

const props = defineProps<{
  forceTab?: string
}>()

// Emits
const emit = defineEmits<{
  selectAgent: [agentId: string]
}>()

const catalog = useAgentCatalogStore()
const userStore = useUserStore()
const prefStore = usePrefStore()
const { userHasFullAccess, userProfile } = storeToRefs(userStore)

const router = useRouter()

const activeTab = ref(
  prefStore.favoriteAgents && Object.keys(prefStore.favoriteAgents).length > 0
    ? 'favorites'
    : 'enterprise'
)

// Watch for forceTab prop changes
watch(
  () => props.forceTab,
  (newTab: string | undefined) => {
    if (newTab) {
      activeTab.value = newTab
    }
  },
  { immediate: true }
)

const userCanEdit = computed(() => userHasFullAccess.value && prefStore.uiConf?.enable_quick_agents)

const profileUpgradeDescription = computed(() => {
  if (!userProfile.value) return ''

  if (!prefStore.uiConf?.enable_quick_agents) {
    return 'User agent creation has been disabled by your administrator.'
  }

  const profileLabel = UserProfileLabelMapper[userProfile.value]
  if (myAgents.value.length === 0) {
    return `You're currently on the ${profileLabel} profile. To access this feature, upgrade to the AI Consumer profile.\n Please contact your admin to request an upgrade.`
  } else {
    return `You're currently on the ${profileLabel} profile. You can still use the Agents you previously created, but you can no longer edit them or create new ones.\n Please contact your admin to request an upgrade to the AI Consumer profile.`
  }
})

const tabsListClass = computed(() => {
  const count = [
    favoriteAgents.value?.length > 0 ? 1 : 0,
    1, // ea agents
    prefStore.uiConf?.enable_quick_agents || myAgents.value?.length > 0 ? 1 : 0,
    1, // shared agents
  ].reduce((a, b) => a + b, 0)
  const gridClass = [`grid-cols-1`, `grid-cols-1`, `grid-cols-2`, `grid-cols-3`, `grid-cols-4`]
  // Avoid possible issues with tailwind purge
  return count <= 4 ? gridClass[count] : gridClass[3] // shouldn't happen
})
// Mock data enrichment function
function enrichAgentData(agent: any) {
  return {
    ...agent,
    description:
      agent.description ||
      "This agent helps you with various tasks and queries. It's designed to provide accurate and helpful responses.",
    exampleQuestions: agent.exampleQuestions || null,
    owner: agent.owner || 'System',
    lastPublished: agent.lastPublished || agent.published_at || null,
  }
}

// Compute agent groups
const enterpriseAgents = computed(() =>
  catalog.agents.filter((a) => a.isEnterprise).map(enrichAgentData)
)

const myAgents = computed(() =>
  catalog.agents
    .filter((a) => !a.isShared && !a.isEnterprise && a.status === 'active')
    .map(enrichAgentData)
)

const sharedAgents = computed(() =>
  catalog.agents.filter((a) => a.isShared && !a.isEnterprise).map(enrichAgentData)
)

const favoriteAgents = computed(() => {
  const favoriteIds = prefStore.favoriteAgents
  return catalog.agents
    .filter((a) => favoriteIds[a.id] && a.status !== 'draft')
    .map(enrichAgentData)
})

// Start conversation with agent
function startConversationWithAgent(agentId: string) {
  emit('selectAgent', agentId)
}

// Start creating agent
function createNewAgent() {
  WT1iser.createAgent()
  router.push({ name: 'NewAgent', query: { new: Date.now().toString() } })
}

async function toggleFavoriteAgent(agentId: string) {
  const isFavorite = !!prefStore.favoriteAgents[agentId]
  await prefStore.toggleFavoriteAgent(agentId, !isFavorite)
}
</script>

<template>
  <div
    :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CONTAINER"
    class="max-w-7xl mx-auto px-2 lg:px-8"
  >
    <!-- Logo and Title -->
    <div class="text-center mb-6 sm:pt-16 md:pt-24">
      <h1
        :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.TITLE"
        class="text-3xl font-bold text-primary-alpha-dark-70 mb-1"
      >
        Agents Library
      </h1>
      <p
        :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.SUBTITLE"
        class="text-foreground max-w-2xl mx-auto text-[20px]"
      >
        Uncover all the agents available in Agent Hub
      </p>
    </div>

    <!-- Desktop Tabs (hidden on mobile) -->
    <Tabs
      :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.TABS_CONTAINER"
      v-model="activeTab"
      class="w-full hidden md:block"
    >
      <div class="xl:px-[100px]">
        <TabsList class="grid w-full mb-6 h-10" :class="tabsListClass">
          <TabsTrigger
            v-if="favoriteAgents.length > 0"
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.TAB_FAVORITES"
            value="favorites"
            class="flex items-center gap-2 hover:text-primary-alpha-dark-70 transition-colors duration-200"
          >
            <i class="dku-icon-star-outline-16"></i>
            Favorite Agents
            <span
              :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.FAVORITES_COUNT"
              class="text-xs px-2 py-1 rounded-full"
              :class="
                activeTab === 'favorites'
                  ? 'bg-primary-alpha-light-30 text-foreground'
                  : 'bg-gray-200 text-foreground'
              "
            >
              {{ favoriteAgents.length }}
            </span>
          </TabsTrigger>

          <TabsTrigger
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.TAB_ENTERPRISE"
            value="enterprise"
            class="flex items-center gap-2 hover:text-primary-alpha-dark-70 transition-colors duration-200"
          >
            <i class="dku-icon-briefcase-20"></i>
            Enterprise Agents
            <span
              :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.ENTERPRISE_COUNT"
              class="text-xs px-2 py-1 rounded-full"
              :class="
                activeTab === 'enterprise'
                  ? 'bg-primary-alpha-light-30 text-foreground'
                  : 'bg-gray-200 text-foreground'
              "
            >
              {{ enterpriseAgents.length }}
            </span>
          </TabsTrigger>

          <TabsTrigger
            v-if="prefStore.uiConf?.enable_quick_agents || myAgents.length > 0"
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.TAB_MY_AGENTS"
            value="myAgents"
            class="flex items-center gap-2 hover:text-primary-alpha-dark-70 transition-colors duration-200"
          >
            <i class="dku-icon-user-20"></i>
            My Agents
            <span
              :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.MY_AGENTS_COUNT"
              class="text-xs px-2 py-1 rounded-full"
              :class="
                activeTab === 'myAgents'
                  ? 'bg-primary-alpha-light-30 text-foreground'
                  : 'bg-gray-200 text-foreground'
              "
            >
              {{ myAgents.length }}
            </span>
          </TabsTrigger>

          <TabsTrigger
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.TAB_SHARED"
            value="shared"
            class="flex items-center gap-2 hover:text-primary-alpha-dark-70 transition-colors duration-200"
          >
            <div class="flex items-center gap-1">
              <i class="dku-icon-share-20"></i>
            </div>
            Agents shared with me
            <span
              :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.SHARED_COUNT"
              class="text-xs px-2 py-1 rounded-full"
              :class="
                activeTab === 'shared'
                  ? 'bg-primary-alpha-light-30 text-foreground'
                  : 'bg-gray-200 text-foreground'
              "
            >
              {{ sharedAgents.length }}
            </span>
          </TabsTrigger>
        </TabsList>
      </div>

      <!-- Favorite Agents Tab -->
      <TabsContent
        v-if="favoriteAgents.length > 0"
        :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.FAVORITES_SECTION"
        value="favorites"
        class="mt-0"
      >
        <div
          v-if="favoriteAgents.length > 0"
          class="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
        >
          <AgentCard
            v-for="agent in favoriteAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
          />
        </div>
        <div
          v-else
          :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.EMPTY_FAVORITES"
          class="text-center py-12"
        >
          <p class="text-foreground text-lg">No favorite agents available.</p>
        </div>
      </TabsContent>

      <!-- Enterprise Agents Tab -->
      <TabsContent
        :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.ENTERPRISE_SECTION"
        value="enterprise"
        class="mt-0"
      >
        <div
          v-if="enterpriseAgents.length > 0"
          class="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
        >
          <AgentCard
            v-for="agent in enterpriseAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
          />
        </div>
        <div
          v-else
          :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.EMPTY_ENTERPRISE"
          class="text-center py-12"
        >
          <p class="text-foreground text-lg">No enterprise agents available.</p>
        </div>
      </TabsContent>

      <!-- My Agents Tab -->
      <TabsContent
        :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.MY_AGENTS_SECTION"
        value="myAgents"
        class="mt-0"
      >
        <!-- Profile Upgrade Info Card -->
        <Alert
          v-if="!userCanEdit"
          :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.PROFILE_UPGRADE_ALERT"
          variant="info"
          class="mb-4"
        >
          <i class="dku-icon-info-circle-outline-16 h-4 w-4"></i>
          <AlertTitle :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.PROFILE_UPGRADE_TITLE">{{
            !prefStore.uiConf?.enable_quick_agents
              ? 'User agent creation has been disabled'
              : 'Upgrade profile to create or edit agents'
          }}</AlertTitle>
          <AlertDescription
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.PROFILE_UPGRADE_DESCRIPTION"
            v-if="userProfile"
          >
            {{ profileUpgradeDescription }}
          </AlertDescription>
        </Alert>
        <div class="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
          <!-- Create New Agent Card or Info Card -->
          <div
            v-if="userCanEdit"
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CREATE_AGENT_CARD"
            @click="createNewAgent"
            class="border-2 border-dashed border rounded-lg p-6 text-center cursor-pointer hover:border-primary-hover hover:bg-primary-alpha-light-5 transition-colors duration-200 h-[163px]"
          >
            <div class="flex items-center justify-center h-full">
              <i
                :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CREATE_AGENT_ICON"
                class="dku-icon-plus-20 text-foreground text-xl mr-2"
              ></i>
              <h3
                :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CREATE_AGENT_TEXT"
                class="text-lg"
              >
                Create a new agent
              </h3>
            </div>
          </div>

          <!-- Existing Agent Cards -->
          <AgentCard
            v-for="agent in myAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
            :is-my-agent="true"
          />
        </div>
      </TabsContent>

      <!-- Shared Agents Tab -->
      <TabsContent
        :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.SHARED_SECTION"
        value="shared"
        class="mt-0"
      >
        <div
          v-if="sharedAgents.length > 0"
          class="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
        >
          <AgentCard
            v-for="agent in sharedAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
          />
        </div>
        <div
          v-else
          :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.EMPTY_SHARED"
          class="text-center py-12"
        >
          <p class="text-foreground text-lg">No agents have been shared with you yet</p>
        </div>
      </TabsContent>
    </Tabs>

    <!-- Mobile Headers and Sections (hidden on desktop) -->
    <div class="md:hidden space-y-8">
      <!-- Favorite Agents Section -->
      <div v-if="favoriteAgents.length > 0">
        <div
          :data-testid="AGENTS_LIBRARY_TEST_IDS.MOBILE.FAVORITES_HEADER"
          class="flex items-center gap-2 mb-4"
        >
          <i class="dku-icon-star-20 text-foreground"></i>
          <h2 class="text-xl font-semibold text-foreground">Favorite Agents</h2>
          <span class="text-xs bg-gray-200 text-foreground px-2 py-1 rounded-full">
            {{ favoriteAgents.length }}
          </span>
        </div>
        <div class="grid gap-4 grid-cols-1">
          <AgentCard
            v-for="agent in favoriteAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
          />
        </div>
      </div>

      <!-- Enterprise Agents Section -->
      <div>
        <div
          :data-testid="AGENTS_LIBRARY_TEST_IDS.MOBILE.ENTERPRISE_HEADER"
          class="flex items-center gap-2 mb-4"
        >
          <i class="dku-icon-briefcase-20 text-foreground"></i>
          <h2 class="text-xl font-semibold text-foreground">Enterprise Agents</h2>
          <span class="text-xs bg-gray-200 text-foreground px-2 py-1 rounded-full">
            {{ enterpriseAgents.length }}
          </span>
        </div>
        <div
          v-if="enterpriseAgents.length === 0"
          :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.EMPTY_ENTERPRISE"
          class="text-center py-8"
        >
          <p class="text-foreground text-lg">No enterprise agents available.</p>
        </div>
        <div v-if="enterpriseAgents.length > 0" class="grid gap-4 grid-cols-1">
          <AgentCard
            v-for="agent in enterpriseAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
          />
        </div>
      </div>

      <!-- My Agents Section -->
      <div v-if="prefStore.uiConf?.enable_quick_agents || myAgents.length > 0">
        <div
          :data-testid="AGENTS_LIBRARY_TEST_IDS.MOBILE.MY_AGENTS_HEADER"
          class="flex items-center gap-2 mb-4"
        >
          <i class="dku-icon-user-20 text-foreground"></i>
          <h2 class="text-xl font-semibold text-foreground">My Agents</h2>
          <span class="text-xs bg-gray-200 text-foreground px-2 py-1 rounded-full">
            {{ myAgents.length }}
          </span>
        </div>
        <!-- No explicit empty state for My Agents on mobile, as the dashed card is always present -->
        <div class="grid gap-4 grid-cols-1">
          <!-- Create New Agent Card or Info Card -->
          <div
            v-if="userCanEdit"
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CREATE_AGENT_CARD"
            @click="createNewAgent"
            class="border-2 border-dashed border-primary rounded-lg p-6 text-center cursor-pointer hover:border-primary-hover hover:bg-primary-alpha-light-5 transition-colors duration-200"
          >
            <div class="flex items-center justify-center h-full">
              <i
                :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CREATE_AGENT_ICON"
                class="dku-icon-plus-20 text-foreground text-xl mr-2"
              ></i>
              <h3
                :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.CREATE_AGENT_TEXT"
                class="text-lg"
              >
                Create a new agent
              </h3>
            </div>
          </div>

          <!-- Profile Upgrade Info Card -->
          <Alert
            v-if="!userHasFullAccess"
            :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.PROFILE_UPGRADE_ALERT"
            variant="info"
          >
            <i class="dku-icon-info-circle-outline-16"></i>
            <AlertTitle :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.PROFILE_UPGRADE_TITLE"
              >Upgrade profile to create or edit agents</AlertTitle
            >
            <AlertDescription
              :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.PROFILE_UPGRADE_DESCRIPTION"
              v-if="userProfile"
            >
              {{ profileUpgradeDescription }}
            </AlertDescription>
          </Alert>

          <!-- Existing Agent Cards -->
          <AgentCard
            v-for="agent in myAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
            :is-my-agent="true"
          />
        </div>
      </div>

      <!-- Shared Agents Section -->
      <div>
        <div
          :data-testid="AGENTS_LIBRARY_TEST_IDS.MOBILE.SHARED_HEADER"
          class="flex items-center gap-2 mb-4"
        >
          <div class="flex items-center gap-1">
            <i class="dku-icon-share-20 text-foreground"></i>
          </div>
          <h2 class="text-xl font-semibold text-foreground">Agents Shared with me</h2>
          <span class="text-xs bg-gray-200 text-foreground px-2 py-1 rounded-full">
            {{ sharedAgents.length }}
          </span>
        </div>
        <div
          v-if="sharedAgents.length === 0"
          :data-testid="AGENTS_LIBRARY_TEST_IDS.AGENTS_LIBRARY.EMPTY_SHARED"
          class="text-center py-8"
        >
          <p class="text-foreground text-lg">No agents have been shared with you yet</p>
        </div>
        <div v-if="sharedAgents.length > 0" class="grid gap-4 grid-cols-1">
          <AgentCard
            v-for="agent in sharedAgents"
            :key="agent.id"
            :agent="agent"
            @select="startConversationWithAgent"
            @toggleFavorite="toggleFavoriteAgent"
            :is-favorite="prefStore.favoriteAgents[agent.id]"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
