<template>
  <div
    :data-testid="testIds.container"
    @click="$emit('select', agent.id)"
    class="group relative overflow-hidden bg-white rounded-lg border border-gray-200 hover:border-primary-alpha-dark-80 hover:shadow-lg transition-all duration-300 cursor-pointer hover:transform hover:scale-[1.02] md:max-h-[163px]"
  >
    <div class="flex flex-col p-3 px-5 py-4 relative z-10 h-[163px]">
      <!-- Header -->
      <div class="flex items-baseline justify-between w-full">
        <!-- Left side: Agent Icon + Name -->
        <div class="flex items-baseline space-x-2 min-w-0 flex-1">
          <!-- Agent Icon -->
          <i
            :class="agentIcon"
            :data-testid="testIds.icon"
            class="text-gray-700 border border-transparent rounded-sm transition-colors group-hover:text-primary-alpha-dark-80 flex-shrink-0 -translate-y-[-4px]"
          ></i>

          <!-- Agent Name -->
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger as-child>
                <h3
                  ref="nameElement"
                  :data-testid="testIds.name"
                  class="font-semibold line-clamp-1 group-hover:text-primary-hover min-w-0"
                >
                  {{ displayName }}
                </h3>
              </TooltipTrigger>
              <TooltipContent :hide-arrow="true" v-if="isNameTruncated">
                <p>{{ displayName }}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>

        <!-- Right side: Status badges -->
        <div class="flex items-baseline space-x-2 flex-shrink-0">
          <!-- Shared badge -->
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger as-child>
                <Badge
                  v-if="agent.shareCount && agent.shareCount > 0"
                  :data-testid="testIds.shareCount"
                  variant="secondary"
                  class="text-xs"
                >
                  <Users class="lucide-icon-small mr-1" />
                  {{ agent.shareCount }}
                </Badge>
              </TooltipTrigger>
              <TooltipContent :hide-arrow="true">
                <p>
                  Shared with {{ agent.shareCount }} {{ agent.shareCount === 1 ? 'user' : 'users' }}
                </p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>

          <!-- Favorite Icon -->
          <div @click.stop="$emit('toggleFavorite', agent.id)" class="cursor-pointer z-10">
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger as-child>
                  <i
                    class="cursor-pointer"
                    :class="[
                      hover || isFavorite
                        ? 'dku-icon-star-fill-16 text-[#F9BD38]'
                        : 'dku-icon-star-outline-16 text-card-foreground',
                    ]"
                    @mouseenter="hover = true"
                    @mouseleave="hover = false"
                  ></i>
                </TooltipTrigger>
                <TooltipContent :hide-arrow="true">
                  <p>
                    {{
                      isFavorite
                        ? 'Remove this agent from your list of favorites'
                        : 'Mark this agent as favorite'
                    }}
                  </p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>

          <!-- Dropdown Menu -->
          <div @click.stop class="cursor-pointer z-10" v-if="props.isMyAgent">
            <DropdownMenu>
              <DropdownMenuTrigger>
                <Button variant="ghost" class="px-0 py-0">
                  <i class="dku-icon-menu-vertical-dots-16 text-foreground"></i>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <Tooltip>
                  <TooltipTrigger as-child>
                    <div>
                      <DropdownMenuItem
                        :disabled="!userCanEdit"
                        @click.stop="
                          () => router.push({ name: 'EditAgent', params: { id: agent.id } })
                        "
                      >
                        <i class="dku-icon-edit-16"></i>Edit
                      </DropdownMenuItem>
                      <DropdownMenuItem :disabled="!userCanEdit" @click.stop="openShareDialog()">
                        <i class="dku-icon-share-16"></i>Share
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        :disabled="!userCanEdit"
                        class="text-destructive"
                        @click.stop="() => confirmDelete(agent.id)"
                      >
                        <i class="dku-icon-trash-16"></i>Delete
                      </DropdownMenuItem>
                    </div>
                  </TooltipTrigger>
                  <TooltipContent :hide-arrow="true" v-if="!userCanEdit">
                    <p>
                      <template v-if="!prefStore.uiConf?.enable_quick_agents">
                        "My Agents" creation has been disabled.
                      </template>
                      <template v-else>
                        Your profile has been downgraded, which limits editing rights.<br />
                        To regain editing access, please contact your administrator to request a
                        profile upgrade.
                      </template>
                    </p>
                  </TooltipContent>
                </Tooltip>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>

      <!-- Description -->
      <p
        :data-testid="testIds.description"
        class="text-sm text-muted-foreground min-h-description flex-1 overflow-y-auto mt-[6px]"
      >
        {{ description }}
      </p>

      <!-- Metadata -->
      <div
        class="pt-2 border-t mt-4 border-gray-100 flex items-baseline justify-between text-xs transition-colors group-hover:border-primary-alpha-dark-80"
      >
        <div class="flex items-center gap-2">
          <!-- Keep items-center here for icon+text alignment -->
          <div class="flex items-center text-gray-500">
            <User class="lucide-icon-small mr-1" />
            <span :data-testid="testIds.owner">{{ ownerName }}</span>
          </div>
          <div class="flex items-center text-gray-500">
            <Calendar class="lucide-icon-small mr-1" />
            <span :data-testid="testIds.date">{{ formattedDate }}</span>
          </div>
        </div>
        <div class="flex items-baseline">
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger>
                <i class="dku-icon-dataiku-16 -translate-y-[-5px]"></i>
              </TooltipTrigger>
              <TooltipContent :hide-arrow="true">
                <p>Built in Dataiku</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>
      </div>
    </div>

    <!-- Delete Agent Dialog -->
    <AlertDialog v-model:open="deleteDialogOpen">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle><i class="dku-icon-trash-16 mr-2"></i>Delete Agent</AlertDialogTitle>
          <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction class="bg-red-600 text-white hover:bg-red-700" @click="doDelete">
            Delete
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>

    <!-- Share Agent Dialog -->
    <ShareAgent
      :open="showShareDialog"
      :agentId="agent.id"
      :agentName="agent.name"
      @update:open="showShareDialog = $event"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { Calendar, User, Users } from 'lucide-vue-next'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@/components/ui/dropdown-menu'
import { generateAgentCardTestIds } from './agents-library-testids'
import { Button } from '@/components/ui/button'
import { useRouter } from 'vue-router'
import ShareAgent from '@/components/ShareAgent.vue'
import { toast } from 'vue-sonner'
import { API } from '@/Api'
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from '@/components/ui/alert-dialog'
import { usePrefStore } from '@/store/prefStore'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/userStore'

const router = useRouter()
const userStore = useUserStore()
const prefStore = usePrefStore()
const { userHasFullAccess } = storeToRefs(userStore)
const userCanEdit = computed(() => userHasFullAccess.value && prefStore.uiConf?.enable_quick_agents)

interface AgentCardProps {
  agent: {
    id: string
    name: string
    status?: 'active' | 'draft'
    isShared?: boolean
    isEnterprise?: boolean
    published_version?: { name: string }
    description?: string
    exampleQuestions?: string[]
    owner?: { name: string; id?: string }
    lastPublished?: string
    published_at?: string
    shareCount?: number
  }
  isMyAgent?: boolean
  isFavorite: boolean
}

const props = defineProps<AgentCardProps>()
defineEmits<{
  (e: 'select', id: string): void
  (e: 'toggleFavorite', id: string): void
}>()

const hover = ref(false)

// Test IDs
const testIds = computed(() => generateAgentCardTestIds(props.agent.id))

// Computed properties
const displayName = computed(() => {
  if (props.agent.published_version?.name) {
    return props.agent.published_version.name
  }
  return props.agent.name || '(unnamed)'
})

const description = computed(() => props.agent.description || 'Not available')

const ownerName = computed(() => props.agent.owner || 'Unknown')

const agentIcon = computed(() => {
  if (props.agent.isEnterprise) {
    return 'dku-icon-briefcase-20'
  } else if (props.agent.isShared) {
    return 'dku-icon-share-20'
  } else {
    return 'dku-icon-user-20'
  }
})

const formattedDate = computed(() => {
  const dateStr = props.agent.published_at || props.agent.lastPublished
  if (!dateStr) return props.agent.isEnterprise ? 'N/A' : 'Not published'

  try {
    const date = new Date(dateStr)
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

    if (diffDays === 0) return 'Today'
    if (diffDays === 1) return 'Yesterday'
    if (diffDays < 7) return `${diffDays} days ago`
    if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`
    if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`

    return date.toLocaleDateString()
  } catch {
    return props.agent.isEnterprise ? 'N/A' : 'Not published'
  }
})

// Ref for truncation detection
const nameElement = ref<HTMLElement | null>(null)

/**
 * Detects if the agent name text is truncated and needs a tooltip
 * Uses a reliable method that works with line-clamp CSS
 */
const isNameTruncated = computed(() => {
  if (!nameElement.value) return false

  const element = nameElement.value

  // Create a temporary element to measure the full text width
  const temp = document.createElement('span')
  temp.style.visibility = 'hidden'
  temp.style.position = 'absolute'
  temp.style.whiteSpace = 'nowrap'
  temp.style.font = window.getComputedStyle(element).font
  temp.textContent = displayName.value

  document.body.appendChild(temp)
  const fullWidth = temp.offsetWidth
  document.body.removeChild(temp)

  // Compare with the container's available width
  return fullWidth > element.offsetWidth
})

// Delete agent logic
// TODO: code duplication from AgentsSidebar.vue
const deleteDialogOpen = ref(false)
const agentToDelete = ref<string | null>(null)
const showShareDialog = ref(false)
function confirmDelete(id: string) {
  agentToDelete.value = id
  deleteDialogOpen.value = true
}

function openShareDialog() {
  showShareDialog.value = true
}
async function doDelete() {
  if (!agentToDelete.value) return
  try {
    await API.deleteAgent(agentToDelete.value)
    toast.success('Agent deleted')

    // Remove from favorites if it exists
    const prefStore = usePrefStore()
    if (prefStore.favoriteAgents[agentToDelete.value]) {
      prefStore.toggleFavoriteAgent(agentToDelete.value, false)
    }
  } catch {
    toast.error('Failed to delete agent')
  } finally {
    deleteDialogOpen.value = false
    agentToDelete.value = null
  }
}
</script>

<style scoped>
/* Lucide icons size */
.lucide-icon-small {
  width: 0.75rem;
  height: 0.75rem;
}

/* Line clamp utilities */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  line-clamp: 1;
}

/* Min height for description */
.min-h-description {
  min-height: 2.5rem;
}
</style>
