<template>
  <div class="space-y-6">
    <div>
      <h3 class="text-lg font-medium mb-4">Review & Complete</h3>
      <p class="text-gray-600 mb-6">Review your setup and complete the wizard to start using your co-op tool.</p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- Members Summary -->
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h4 class="font-medium">Members ({{ members.length }})</h4>
            <UBadge :color="membersValid ? 'green' : 'red'" variant="subtle">
              {{ membersValid ? 'Valid' : 'Incomplete' }}
            </UBadge>
          </div>
        </template>
        
        <div class="space-y-3">
          <div v-for="member in members" :key="member.id" class="flex items-center justify-between text-sm">
            <div>
              <span class="font-medium">{{ member.displayName || 'Unnamed Member' }}</span>
              <span v-if="member.roleFocus" class="text-gray-500 ml-1">({{ member.roleFocus }})</span>
            </div>
            <div class="text-right text-xs text-gray-500">
              <div>{{ member.payRelationship || 'No relationship set' }}</div>
              <div>{{ member.capacity?.targetHours || 0 }}h/month</div>
            </div>
          </div>
          
          <div class="pt-3 border-t border-gray-100">
            <div class="grid grid-cols-2 gap-4 text-xs">
              <div>
                <span class="text-gray-600">Total capacity:</span>
                <span class="font-medium ml-1">{{ totalCapacity }}h</span>
              </div>
              <div>
                <span class="text-gray-600">Avg external:</span>
                <span class="font-medium ml-1">{{ avgExternal }}%</span>
              </div>
            </div>
          </div>
        </div>
      </UCard>

      <!-- Policies Summary -->
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h4 class="font-medium">Policies</h4>
            <UBadge :color="policiesValid ? 'green' : 'red'" variant="subtle">
              {{ policiesValid ? 'Valid' : 'Incomplete' }}
            </UBadge>
          </div>
        </template>
        
        <div class="space-y-3 text-sm">
          <div class="flex justify-between">
            <span class="text-gray-600">Equal hourly wage:</span>
            <span class="font-medium">€{{ policies.equalHourlyWage || 0 }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Payroll on-costs:</span>
            <span class="font-medium">{{ policies.payrollOncostPct || 0 }}%</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Savings target:</span>
            <span class="font-medium">{{ policies.savingsTargetMonths || 0 }} months</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Cash cushion:</span>
            <span class="font-medium">€{{ policies.minCashCushionAmount || 0 }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Deferred cap:</span>
            <span class="font-medium">{{ policies.deferredCapHoursPerQtr || 0 }}h/qtr</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">Volunteer flows:</span>
            <span class="font-medium">{{ policies.volunteerScope.allowedFlows.length }} types</span>
          </div>
        </div>
      </UCard>

      <!-- Costs Summary -->
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h4 class="font-medium">Overhead Costs ({{ overheadCosts.length }})</h4>
            <UBadge color="blue" variant="subtle">Optional</UBadge>
          </div>
        </template>
        
        <div v-if="overheadCosts.length === 0" class="text-sm text-gray-500 text-center py-4">
          No overhead costs added
        </div>
        
        <div v-else class="space-y-2">
          <div v-for="cost in overheadCosts.slice(0, 3)" :key="cost.id" class="flex justify-between text-sm">
            <span class="text-gray-700">{{ cost.name }}</span>
            <span class="font-medium">€{{ cost.amount || 0 }}</span>
          </div>
          <div v-if="overheadCosts.length > 3" class="text-xs text-gray-500">
            +{{ overheadCosts.length - 3 }} more items
          </div>
          
          <div class="pt-2 border-t border-gray-100">
            <div class="flex justify-between text-sm font-medium">
              <span>Monthly total:</span>
              <span>€{{ totalMonthlyCosts }}</span>
            </div>
          </div>
        </div>
      </UCard>

      <!-- Revenue Summary -->
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h4 class="font-medium">Revenue Streams ({{ streams.length }})</h4>
            <UBadge :color="streamsValid ? 'green' : 'red'" variant="subtle">
              {{ streamsValid ? 'Valid' : 'Incomplete' }}
            </UBadge>
          </div>
        </template>
        
        <div v-if="streams.length === 0" class="text-sm text-gray-500 text-center py-4">
          No revenue streams added
        </div>
        
        <div v-else class="space-y-3">
          <div v-for="stream in streams.slice(0, 3)" :key="stream.id" class="space-y-1">
            <div class="flex justify-between text-sm">
              <span class="font-medium">{{ stream.name || 'Unnamed Stream' }}</span>
              <span class="text-gray-600">{{ stream.targetPct || 0 }}%</span>
            </div>
            <div class="flex justify-between text-xs text-gray-500">
              <span>{{ stream.category }} • {{ stream.certainty }}</span>
              <span>€{{ stream.targetMonthlyAmount || 0 }}/mo</span>
            </div>
          </div>
          
          <div v-if="streams.length > 3" class="text-xs text-gray-500">
            +{{ streams.length - 3 }} more streams
          </div>
          
          <div class="pt-3 border-t border-gray-100">
            <div class="grid grid-cols-2 gap-4 text-xs">
              <div>
                <span class="text-gray-600">Target % total:</span>
                <span class="font-medium ml-1" :class="totalTargetPct === 100 ? 'text-green-600' : 'text-red-600'">
                  {{ totalTargetPct }}%
                </span>
              </div>
              <div>
                <span class="text-gray-600">Monthly target:</span>
                <span class="font-medium ml-1">€{{ totalMonthlyTarget }}</span>
              </div>
            </div>
          </div>
        </div>
      </UCard>
    </div>

    <!-- Overall Status -->
    <div class="bg-gray-50 rounded-lg p-4">
      <h4 class="font-medium text-sm mb-3">Setup Status</h4>
      
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
        <div class="flex items-center gap-2">
          <UIcon 
            :name="membersValid ? 'i-heroicons-check-circle' : 'i-heroicons-x-circle'" 
            :class="membersValid ? 'text-green-500' : 'text-red-500'"
            class="w-4 h-4"
          />
          <span class="text-sm">Members</span>
        </div>
        
        <div class="flex items-center gap-2">
          <UIcon 
            :name="policiesValid ? 'i-heroicons-check-circle' : 'i-heroicons-x-circle'" 
            :class="policiesValid ? 'text-green-500' : 'text-red-500'"
            class="w-4 h-4"
          />
          <span class="text-sm">Policies</span>
        </div>
        
        <div class="flex items-center gap-2">
          <UIcon name="i-heroicons-check-circle" class="text-blue-500 w-4 h-4" />
          <span class="text-sm">Costs (Optional)</span>
        </div>
        
        <div class="flex items-center gap-2">
          <UIcon 
            :name="streamsValid ? 'i-heroicons-check-circle' : 'i-heroicons-x-circle'" 
            :class="streamsValid ? 'text-green-500' : 'text-red-500'"
            class="w-4 h-4"
          />
          <span class="text-sm">Revenue</span>
        </div>
      </div>

      <div v-if="!canComplete" class="bg-yellow-100 border border-yellow-200 rounded-md p-3 mb-4">
        <div class="flex items-center gap-2">
          <UIcon name="i-heroicons-exclamation-triangle" class="text-yellow-600 w-4 h-4" />
          <span class="text-sm font-medium text-yellow-800">Complete required sections to finish setup</span>
        </div>
        <ul class="list-disc list-inside text-xs text-yellow-700 mt-2">
          <li v-if="!membersValid">Add at least one member with valid details</li>
          <li v-if="!policiesValid">Set a valid hourly wage and complete policy fields</li>
          <li v-if="!streamsValid">Add at least one revenue stream with valid details</li>
        </ul>
      </div>
    </div>

    <!-- Actions -->
    <div class="flex justify-between items-center pt-6 border-t">
      <UButton variant="ghost" @click="$emit('reset')" color="red">
        Reset All Data
      </UButton>
      
      <div class="flex gap-3">
        <UButton variant="outline" @click="exportSetup">
          Export Setup
        </UButton>
        <UButton 
          @click="completeSetup" 
          :disabled="!canComplete"
          size="lg"
        >
          Complete Setup
        </UButton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
const emit = defineEmits<{
  'complete': []
  'reset': []
}>()

// Stores
const membersStore = useMembersStore()
const policiesStore = usePoliciesStore()
const budgetStore = useBudgetStore()
const streamsStore = useStreamsStore()

// Computed data
const members = computed(() => membersStore.members)
const policies = computed(() => ({
  equalHourlyWage: policiesStore.equalHourlyWage,
  payrollOncostPct: policiesStore.payrollOncostPct,
  savingsTargetMonths: policiesStore.savingsTargetMonths,
  minCashCushionAmount: policiesStore.minCashCushionAmount,
  deferredCapHoursPerQtr: policiesStore.deferredCapHoursPerQtr,
  volunteerScope: policiesStore.volunteerScope
}))
const overheadCosts = computed(() => budgetStore.overheadCosts)
const streams = computed(() => streamsStore.streams)

// Validation
const membersValid = computed(() => membersStore.isValid)
const policiesValid = computed(() => policiesStore.isValid)
const streamsValid = computed(() => streamsStore.hasValidStreams)
const canComplete = computed(() => membersValid.value && policiesValid.value && streamsValid.value)

// Summary calculations
const totalCapacity = computed(() => 
  members.value.reduce((sum, m) => sum + (m.capacity?.targetHours || 0), 0)
)

const avgExternal = computed(() => {
  if (members.value.length === 0) return 0
  const total = members.value.reduce((sum, m) => sum + (m.externalCoveragePct || 0), 0)
  return Math.round(total / members.value.length)
})

const totalMonthlyCosts = computed(() => 
  overheadCosts.value.reduce((sum, c) => sum + (c.amount || 0), 0)
)

const totalTargetPct = computed(() => streamsStore.totalTargetPct)
const totalMonthlyTarget = computed(() => 
  Math.round(streams.value.reduce((sum, s) => sum + (s.targetMonthlyAmount || 0), 0))
)

function completeSetup() {
  if (canComplete.value) {
    // Mark setup as complete in some way (could be a store flag)
    emit('complete')
  }
}

function exportSetup() {
  // Create export data
  const setupData = {
    members: members.value,
    policies: policies.value,
    overheadCosts: overheadCosts.value,
    streams: streams.value,
    exportedAt: new Date().toISOString(),
    version: '1.0'
  }

  // Download as JSON
  const blob = new Blob([JSON.stringify(setupData, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `coop-setup-${new Date().toISOString().split('T')[0]}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}
</script>