<script setup>
import { ref, onMounted, computed } from 'vue'
import { useDealsStore } from '@/stores/deals'

const deals = useDealsStore()
const showNewDealModal = ref(false)
const draggedDeal = ref(null)

const newDeal = ref({
  title: '',
  value: '',
  contactId: '',
  companyId: '',
  expectedCloseDate: ''
})

onMounted(async () => {
  await deals.fetchPipelines()
  if (deals.currentPipeline) {
    await deals.fetchKanban(deals.currentPipeline.id)
  }
})

function formatCurrency(value) {
  return new Intl.NumberFormat('de-DE', { 
    style: 'currency', 
    currency: 'EUR',
    minimumFractionDigits: 0
  }).format(value || 0)
}

function getStageColor(index, total) {
  const colors = ['bg-gray-500', 'bg-blue-500', 'bg-yellow-500', 'bg-orange-500', 'bg-green-500']
  return colors[Math.min(index, colors.length - 1)]
}

function handleDragStart(e, deal) {
  draggedDeal.value = deal
  e.dataTransfer.effectAllowed = 'move'
}

function handleDragOver(e) {
  e.preventDefault()
  e.dataTransfer.dropEffect = 'move'
}

async function handleDrop(e, stageId) {
  e.preventDefault()
  if (draggedDeal.value && draggedDeal.value.stageId !== stageId) {
    await deals.moveDeal(draggedDeal.value.id, stageId)
  }
  draggedDeal.value = null
}

async function createDeal() {
  if (!newDeal.value.title) return
  
  try {
    await deals.createDeal({
      title: newDeal.value.title,
      value: parseFloat(newDeal.value.value) || 0,
      stageId: deals.kanbanData.stages[0]?.id,
      expectedCloseDate: newDeal.value.expectedCloseDate || null
    })
    showNewDealModal.value = false
    newDeal.value = { title: '', value: '', contactId: '', companyId: '', expectedCloseDate: '' }
  } catch (e) {
    console.error('Error creating deal:', e)
  }
}

function calculateStageValue(stageId) {
  const stageDeals = deals.kanbanData.deals[stageId] || []
  return stageDeals.reduce((sum, d) => sum + (d.value || 0), 0)
}
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- Header -->
    <div class="flex items-center justify-between px-6 py-4 border-b border-pulse-border bg-pulse-card">
      <div>
        <h1 class="text-xl font-bold text-white">Sales Pipeline</h1>
        <p class="text-sm text-pulse-muted">{{ deals.currentPipeline?.name || 'Loading...' }}</p>
      </div>
      <button @click="showNewDealModal = true" class="btn-primary">
        <svg class="w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
        </svg>
        Neuer Deal
      </button>
    </div>

    <!-- Kanban Board -->
    <div class="flex-1 overflow-x-auto p-6">
      <div v-if="deals.loading" class="flex items-center justify-center h-64">
        <svg class="animate-spin h-8 w-8 text-primary-500" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
        </svg>
      </div>

      <div v-else class="flex gap-4 h-full min-w-max">
        <div
          v-for="(stage, index) in deals.kanbanData.stages"
          :key="stage.id"
          class="kanban-column flex flex-col"
          @dragover="handleDragOver"
          @drop="handleDrop($event, stage.id)"
        >
          <!-- Stage Header -->
          <div class="p-4 border-b border-pulse-border">
            <div class="flex items-center gap-2 mb-2">
              <div :class="['w-3 h-3 rounded-full', getStageColor(index, deals.kanbanData.stages.length)]"></div>
              <h3 class="font-semibold text-white">{{ stage.name }}</h3>
              <span class="text-xs text-pulse-muted bg-pulse-card px-2 py-0.5 rounded-full">
                {{ (deals.kanbanData.deals[stage.id] || []).length }}
              </span>
            </div>
            <p class="text-sm text-pulse-muted">
              {{ formatCurrency(calculateStageValue(stage.id)) }}
            </p>
          </div>

          <!-- Deals List -->
          <div class="flex-1 overflow-y-auto p-3 space-y-3">
            <div
              v-for="deal in deals.kanbanData.deals[stage.id] || []"
              :key="deal.id"
              class="kanban-card"
              draggable="true"
              @dragstart="handleDragStart($event, deal)"
            >
              <div class="flex items-start justify-between mb-2">
                <h4 class="font-medium text-white text-sm">{{ deal.title }}</h4>
                <span class="text-xs font-semibold text-green-400">
                  {{ formatCurrency(deal.value) }}
                </span>
              </div>
              
              <div v-if="deal.company" class="text-xs text-pulse-muted mb-2">
                🏢 {{ deal.company.name }}
              </div>
              
              <div v-if="deal.contact" class="text-xs text-pulse-muted mb-2">
                👤 {{ deal.contact.name }}
              </div>

              <div class="flex items-center justify-between text-xs">
                <span v-if="deal.expectedCloseDate" class="text-pulse-muted">
                  📅 {{ new Date(deal.expectedCloseDate).toLocaleDateString('de-DE') }}
                </span>
                <span v-if="deal.probability" :class="[
                  'px-2 py-0.5 rounded-full',
                  deal.probability >= 70 ? 'bg-green-500/20 text-green-400' :
                  deal.probability >= 40 ? 'bg-yellow-500/20 text-yellow-400' :
                  'bg-red-500/20 text-red-400'
                ]">
                  {{ deal.probability }}%
                </span>
              </div>
            </div>

            <!-- Empty State -->
            <div 
              v-if="!(deals.kanbanData.deals[stage.id] || []).length"
              class="flex flex-col items-center justify-center py-8 text-pulse-muted"
            >
              <svg class="w-8 h-8 mb-2 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
              </svg>
              <p class="text-sm">Keine Deals</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- New Deal Modal -->
    <Teleport to="body">
      <div v-if="showNewDealModal" class="fixed inset-0 z-50 flex items-center justify-center">
        <div class="absolute inset-0 bg-black/60" @click="showNewDealModal = false"></div>
        <div class="relative card w-full max-w-md mx-4">
          <div class="px-6 py-4 border-b border-pulse-border">
            <h2 class="text-lg font-semibold text-white">Neuer Deal</h2>
          </div>
          <form @submit.prevent="createDeal" class="p-6 space-y-4">
            <div>
              <label class="label">Titel *</label>
              <input v-model="newDeal.title" type="text" class="input" placeholder="z.B. Website Redesign" required />
            </div>
            <div>
              <label class="label">Wert (€)</label>
              <input v-model="newDeal.value" type="number" class="input" placeholder="10000" />
            </div>
            <div>
              <label class="label">Erwarteter Abschluss</label>
              <input v-model="newDeal.expectedCloseDate" type="date" class="input" />
            </div>
            <div class="flex gap-3 pt-2">
              <button type="button" @click="showNewDealModal = false" class="btn-secondary flex-1">
                Abbrechen
              </button>
              <button type="submit" class="btn-primary flex-1">
                Erstellen
              </button>
            </div>
          </form>
        </div>
      </div>
    </Teleport>
  </div>
</template>
