<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 mobileSelectedStage = ref(null)

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

onMounted(async () => {
  await deals.fetchPipelines()
  if (deals.currentPipeline) {
    await deals.fetchKanban(deals.currentPipeline.id)
    // Set first stage as default for mobile
    if (deals.kanbanData.stages?.length) {
      mobileSelectedStage.value = deals.kanbanData.stages[0].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)
}

function getStageDealsCount(stageId) {
  return (deals.kanbanData.deals[stageId] || []).length
}
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 px-4 sm: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 w-full sm:w-auto">
        <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>

    <!-- Loading -->
    <div v-if="deals.loading" class="flex-1 flex items-center justify-center">
      <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>

    <!-- Mobile Stage Tabs -->
    <div v-if="!deals.loading" class="md:hidden border-b border-pulse-border bg-pulse-card">
      <div class="flex overflow-x-auto px-4 py-2 gap-2 -mx-4">
        <button
          v-for="(stage, index) in deals.kanbanData.stages"
          :key="stage.id"
          @click="mobileSelectedStage = stage.id"
          :class="[
            'flex items-center gap-2 px-3 py-2 rounded-lg whitespace-nowrap transition-colors flex-shrink-0',
            mobileSelectedStage === stage.id 
              ? 'bg-primary-500 text-white' 
              : 'bg-pulse-dark text-pulse-muted'
          ]"
        >
          <div :class="['w-2 h-2 rounded-full', getStageColor(index, deals.kanbanData.stages.length)]"></div>
          <span class="text-sm font-medium">{{ stage.name }}</span>
          <span class="text-xs bg-black/20 px-1.5 py-0.5 rounded">
            {{ getStageDealsCount(stage.id) }}
          </span>
        </button>
      </div>
    </div>

    <!-- Mobile Deals List -->
    <div v-if="!deals.loading" class="md:hidden flex-1 overflow-y-auto p-4">
      <div class="mb-4 flex items-center justify-between">
        <p class="text-sm text-pulse-muted">
          {{ formatCurrency(calculateStageValue(mobileSelectedStage)) }} in dieser Phase
        </p>
      </div>
      
      <div class="space-y-3">
        <div
          v-for="deal in deals.kanbanData.deals[mobileSelectedStage] || []"
          :key="deal.id"
          class="card p-4 active:scale-[0.98] transition-transform"
        >
          <div class="flex items-start justify-between mb-2">
            <h4 class="font-medium text-white">{{ deal.title }}</h4>
            <span class="text-sm font-semibold text-green-400">
              {{ formatCurrency(deal.value) }}
            </span>
          </div>
          
          <div v-if="deal.company" class="text-sm text-pulse-muted mb-1">
            🏢 {{ deal.company.name }}
          </div>
          
          <div v-if="deal.contact" class="text-sm 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[mobileSelectedStage] || []).length"
          class="flex flex-col items-center justify-center py-12 text-pulse-muted"
        >
          <svg class="w-12 h-12 mb-3 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>Keine Deals in dieser Phase</p>
        </div>
      </div>
    </div>

    <!-- Desktop Kanban Board -->
    <div v-if="!deals.loading" class="hidden md:block flex-1 overflow-x-auto p-6">
      <div 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">
                {{ getStageDealsCount(stage.id) }}
              </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-end sm:items-center justify-center p-0 sm:p-4">
        <div class="absolute inset-0 bg-black/60" @click="showNewDealModal = false"></div>
        <div class="relative card w-full sm:max-w-md rounded-b-none sm:rounded-b-xl max-h-[90vh] overflow-y-auto">
          <div class="px-4 sm:px-6 py-4 border-b border-pulse-border sticky top-0 bg-pulse-card z-10">
            <div class="flex items-center justify-between">
              <h2 class="text-lg font-semibold text-white">Neuer Deal</h2>
              <button @click="showNewDealModal = false" class="p-2 text-pulse-muted hover:text-white sm:hidden">
                <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>
          <form @submit.prevent="createDeal" class="p-4 sm: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 flex-col-reverse sm:flex-row 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>
