<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { X, ExternalLink } from '@lucide/vue'
import type { AgentNodeData } from '../../composables/useDashboardData'
import { useToast } from '../../composables/useToast'
import Button from '@/components/ui/button/Button.vue'
import Badge from '@/components/ui/Badge.vue'
import Select from '@/components/ui/Select.vue'

const props = defineProps<{
  agent: AgentNodeData
  runtime: string
}>()

const emit = defineEmits<{
  close: []
}>()

const toast = useToast()

interface ModelOption {
  id: string
  name: string
  provider: string
}

const availableModels = ref<ModelOption[]>([])
const selectedModel = ref('')
const currentModel = ref('')
const saving = ref(false)

async function loadModels() {
  try {
    const res = await fetch('/api/dashboard/models', { credentials: 'include' })
    if (res.ok) {
      availableModels.value = await res.json()
    }
  } catch {
    // silent
  }
}

async function loadCurrentModel() {
  try {
    const res = await fetch(`/api/dashboard/agents/${props.agent.id}/model`, { credentials: 'include' })
    if (res.ok) {
      const data = await res.json()
      selectedModel.value = data.model
      currentModel.value = data.model
    }
  } catch {
    // silent
  }
}

async function saveModel() {
  saving.value = true
  try {
    const res = await fetch(`/api/dashboard/agents/${props.agent.id}/model`, {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ model: selectedModel.value }),
    })
    if (res.ok) {
      currentModel.value = selectedModel.value
      toast.success('Model updated successfully')
    } else {
      toast.error('Failed to update model')
    }
  } catch {
    toast.error('Connection error')
  } finally {
    saving.value = false
  }
}

onMounted(async () => {
  await loadModels()
  await loadCurrentModel()
})
</script>

<template>
  <Teleport to="body">
    <div class="modal-overlay" @click.self="$emit('close')">
      <div class="modal-card" :style="{ '--agent-color': agent.color }">
        <!-- Header -->
        <div class="modal-header">
          <div class="modal-title-row">
            <div class="modal-avatar" :style="{ background: `${agent.color}18`, color: agent.color }">
              <span class="avatar-letter">{{ agent.name.charAt(0) }}</span>
            </div>
            <div>
              <h2>{{ agent.name }}</h2>
              <span class="modal-role">{{ agent.role }}</span>
              <a :href="`/agents/${agent.id}`" class="agent-link-btn" title="Open agent config">
                <ExternalLink :size="12" />
              </a>
            </div>
          </div>
          <Button variant="ghost" size="icon" class="h-8 w-8" @click="$emit('close')" aria-label="Close">
            <X :size="16" />
          </Button>
        </div>

        <!-- Status -->
        <section class="modal-section">
          <h3 class="section-label">Status</h3>
          <div class="status-row">
            <Badge
              :variant="agent.active ? 'default' : 'secondary'"
              :class="agent.active ? 'bg-[rgba(81,212,154,0.1)] text-[#51d49a] border-[rgba(81,212,154,0.3)]' : 'bg-[rgba(107,115,133,0.08)] text-[#6b7385] border-[rgba(107,115,133,0.2)]'"
            >
              <span class="status-dot" :class="{ active: agent.active }" />
              {{ agent.active ? 'Active' : 'Idle' }}
            </Badge>
            <span v-if="agent.active" class="footer-badge">Runtime: {{ runtime }}</span>
          </div>
        </section>

        <!-- Description -->
        <p class="modal-desc">{{ agent.description }}</p>

        <!-- Tags -->
        <section class="modal-section">
          <h3 class="section-label">Tags</h3>
          <div class="modal-tags-row">
            <Badge
              v-for="tag in agent.tags"
              :key="tag"
              variant="outline"
              :style="{ background: `${agent.color}18`, color: agent.color, borderColor: `${agent.color}30` }"
            >
              {{ tag }}
            </Badge>
          </div>
        </section>

        <!-- Current Task -->
        <section class="modal-section">
          <h3 class="section-label">Current Task</h3>
          <p class="section-value">
            {{ agent.currentTask }}
            <span v-if="agent.active" class="thinking-dots">
              <span class="thinking-dot blue"></span>
              <span class="thinking-dot violet"></span>
            </span>
          </p>
        </section>

        <!-- Goal + Progress -->
        <section class="modal-section">
          <h3 class="section-label">Goal</h3>
          <p class="section-value">{{ agent.goal }}</p>
          <div class="progress-row">
            <span class="progress-pct">{{ agent.progress }}%</span>
            <div class="progress-track">
              <div class="progress-fill" :style="{ width: `${agent.progress}%` }"></div>
            </div>
          </div>
        </section>

        <!-- Model -->
        <section class="modal-section">
          <h3 class="section-label">Model</h3>
          <div class="model-select-row">
            <Select v-model="selectedModel" class="flex-1 text-xs border-[#a78bfa]">
              <option v-for="m in availableModels" :key="m.id" :value="m.id">
                {{ m.name }} ({{ m.provider }})
              </option>
            </Select>
            <Button
              variant="default"
              size="sm"
              class="bg-[#a78bfa] hover:bg-[#c4b5fd]"
              :disabled="saving || selectedModel === currentModel"
              @click="saveModel"
            >
              {{ saving ? 'Saving...' : 'Save' }}
            </Button>
          </div>
        </section>

        <!-- Footer Stats -->
        <div class="modal-footer">
          <Badge :class="agent.active ? 'bg-[rgba(81,212,154,0.06)] text-[#51d49a] border-[rgba(81,212,154,0.25)]' : 'bg-[rgba(107,115,133,0.04)] text-[#6b7385] border-[rgba(107,115,133,0.15)]'">
            {{ agent.active ? '● Active' : '○ Idle' }}
          </Badge>
          <span v-if="agent.active" class="footer-badge">{{ runtime }}</span>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: grid;
  place-items: center;
  padding: 24px;
  background: rgba(0, 0, 0, 0.55);
  backdrop-filter: blur(4px);
  animation: overlay-in 0.2s ease;
}
@keyframes overlay-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

.modal-card {
  width: min(480px, 100%);
  max-height: 80vh;
  overflow-y: auto;
  padding: 24px;
  background: rgba(18, 22, 30, 0.96);
  border: 1px solid color-mix(in srgb, var(--agent-color) 25%, transparent);
  border-radius: 16px;
  box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
  animation: card-in 0.25s ease;
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
}
@keyframes card-in {
  from { opacity: 0; transform: translateY(12px) scale(0.98); }
  to { opacity: 1; transform: translateY(0) scale(1); }
}
.modal-card::-webkit-scrollbar {
  width: 5px;
}
.modal-card::-webkit-scrollbar-track {
  background: transparent;
}
.modal-card::-webkit-scrollbar-thumb {
  background: rgba(139, 124, 246, 0.2);
  border-radius: 3px;
}

.modal-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px;
}
.modal-title-row {
  display: flex;
  align-items: center;
  gap: 14px;
}
.modal-avatar {
  width: 44px;
  height: 44px;
  display: grid;
  place-items: center;
  border-radius: 12px;
  flex-shrink: 0;
}
.avatar-letter {
  font-size: 18px;
  font-weight: 700;
}
.modal-title-row h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #e8eaf0;
}
.modal-role {
  font-size: 10px;
  color: #6b7385;
  font-weight: 500;
}
.agent-link-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-left: 4px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #6b7385;
  opacity: 0.4;
  cursor: pointer;
  transition: opacity 0.2s;
  flex-shrink: 0;
  text-decoration: none;
  vertical-align: middle;
}
.agent-link-btn:hover {
  opacity: 1;
  color: var(--agent-color);
}

.modal-desc {
  font-size: 11px;
  line-height: 1.55;
  color: #7e8799;
  margin: 0 0 18px;
  padding-bottom: 14px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.modal-section {
  margin-bottom: 16px;
}
.section-label {
  font-size: 9px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: #6b7385;
  margin: 0 0 6px;
}
.section-value {
  margin: 0;
  font-size: 12px;
  color: #e8eaf0;
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Status */
.status-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6b7385;
  transition: all 0.3s ease;
}
.status-dot.active {
  background: #51d49a;
  box-shadow: 0 0 8px rgba(81, 212, 154, 0.6);
  animation: pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.6; transform: scale(1.2); }
}

/* Tags */
.modal-tags-row {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

/* Progress */
.progress-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 8px;
}
.progress-pct {
  font-size: 11px;
  font-weight: 600;
  color: #7e8799;
  flex-shrink: 0;
  font-variant-numeric: tabular-nums;
}
.progress-track {
  flex: 1;
  height: 4px;
  background: rgba(255, 255, 255, 0.06);
  border-radius: 4px;
  overflow: hidden;
}
.progress-fill {
  height: 100%;
  border-radius: 4px;
  background: var(--agent-color);
  transition: width 0.5s ease;
}

/* Thinking Dots */
.thinking-dots {
  display: inline-flex;
  gap: 6px;
  flex-shrink: 0;
}
.thinking-dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
}
.thinking-dot.blue {
  background: #3b82f6;
  box-shadow: 0 0 8px #3b82f6;
  animation: pulse-dot-blue 1.2s ease-in-out infinite;
}
.thinking-dot.violet {
  background: #8b7cf6;
  box-shadow: 0 0 8px #8b7cf6;
  animation: pulse-dot-violet 1.8s ease-in-out infinite 0.3s;
}
@keyframes pulse-dot-blue {
  0%, 100% { opacity: 0.4; transform: scale(0.7); }
  50% { opacity: 1; transform: scale(1.3); }
}
@keyframes pulse-dot-violet {
  0%, 100% { opacity: 0.3; transform: scale(0.6); }
  50% { opacity: 1; transform: scale(1.4); }
}

/* Footer */
.modal-footer {
  display: flex;
  gap: 10px;
  padding-top: 14px;
  margin-top: 6px;
  border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.footer-badge {
  font-size: 9px;
  font-weight: 600;
  padding: 4px 10px;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.06);
  color: #7e8799;
}

/* Model Selector */
.model-select-row {
  display: flex;
  gap: 8px;
  align-items: center;
}
</style>
