<script setup lang="ts">
const route = useRoute()
const id = decodeURIComponent(route.params.id as string)

const { data, pending, error, refresh } = useWorkload(`/tasks/${id}`)
const task = computed(() => data.value?.data)

const taskType = computed(() => {
  const parts = id?.split(':') ?? []
  return parts[1] || 'unknown'
})

const isQuote = computed(() => taskType.value === 'quote')
const isSolicitation = computed(() => taskType.value === 'solicitation')

// State-based actions
const isSubmitResponseOpen = ref(false)
const isApproveOpen = ref(false)
const isCompleteOpen = ref(false)

const submitting = ref(false)
const toast = useToast()
const { $workload } = useNuxtApp()

// Quote response form
const quoteForm = ref({
  quote_id: '',
  valid_until: '',
  recorded_by: '',
  document_url: '',
  plans: [{ plan_id: '', name: '', premium: '', coverage_details: {} }]
})

function addPlan() {
  quoteForm.value.plans.push({ plan_id: '', name: '', premium: '', coverage_details: {} })
}

function removePlan(i: number) {
  quoteForm.value.plans.splice(i, 1)
}

function addCoverageDetail(plan: any) {
  const key = newCoverageKey.value.trim()
  const value = newCoverageValue.value.trim()
  if (key && value) {
    plan.coverage_details[key] = value
    newCoverageKey.value = ''
    newCoverageValue.value = ''
  }
}

const newCoverageKey = ref('')
const newCoverageValue = ref('')

async function submitResponse() {
  submitting.value = true
  try {
    await $workload(`/tasks/${id}/submit`, {
      method: 'POST',
      body: {
        quote_id: quoteForm.value.quote_id,
        valid_until: quoteForm.value.valid_until,
        recorded_by: quoteForm.value.recorded_by,
        document_url: quoteForm.value.document_url || undefined,
        plans: quoteForm.value.plans.map(p => ({
          plan_id: p.plan_id,
          name: p.name,
          premium: parseFloat(p.premium) || 0,
          coverage_details: p.coverage_details
        }))
      }
    })
    toast.add({ title: 'Response submitted', color: 'green' })
    isSubmitResponseOpen.value = false
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    submitting.value = false
  }
}

async function confirmDelivery() {
  submitting.value = true
  try {
    await $workload(`/tasks/${id}/submit`, { method: 'POST' })
    toast.add({ title: 'Delivery confirmed', color: 'green' })
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    submitting.value = false
  }
}

async function approveSubmission() {
  submitting.value = true
  try {
    await $workload(`/tasks/${id}/approve`, { method: 'POST' })
    toast.add({ title: 'Submission approved', color: 'green' })
    isApproveOpen.value = false
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    submitting.value = false
  }
}

async function completeTask() {
  submitting.value = true
  try {
    await $workload(`/tasks/${id}/complete`, { method: 'POST', body: { completed_by: 'admin' } })
    toast.add({ title: 'Task completed', color: 'green' })
    isCompleteOpen.value = false
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    submitting.value = false
  }
}

const statusColor = (status: string) => {
  switch (status) {
    case 'created': return 'yellow'
    case 'draft': return 'blue'
    case 'approved': return 'green'
    case 'completed': return 'gray'
    default: return 'gray'
  }
}

const policyTypeColor = (type: string) => {
  switch (type) {
    case 'car': return 'blue'
    case 'life': return 'purple'
    case 'fire': return 'orange'
    default: return 'gray'
  }
}

const formatDate = (d: string) => d
  ? new Date(d).toLocaleDateString('es-PA', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
  : '—'
</script>

<template>
  <div class="p-8 space-y-8 bg-gray-50 min-h-screen">
    <NuxtLink to="/workload">
      <UButton icon="i-heroicons-arrow-left" color="gray" variant="ghost">Back to Workload</UButton>
    </NuxtLink>

    <UAlert v-if="error" color="red" variant="soft" title="Failed to load task" :description="error.message" />
    <div v-else-if="pending" class="space-y-4"><UCard v-for="n in 3" :key="n"><div class="h-32 animate-pulse bg-gray-200 rounded" /></UCard></div>

    <template v-else-if="task">
      <!-- Header -->
      <div class="flex justify-between items-start">
        <div class="space-y-2">
          <div class="flex items-center gap-2 flex-wrap">
            <UBadge :color="statusColor(task.status)" variant="soft">{{ task.status }}</UBadge>
            <UBadge :color="policyTypeColor(task.task_info?.policy_type)" variant="outline">{{ task.task_info?.policy_type?.toUpperCase() || '—' }}</UBadge>
            <UBadge color="gray" variant="outline">{{ taskType }}</UBadge>
          </div>
          <h1 class="text-xl font-bold text-slate-900 font-mono">{{ task.application_id }}</h1>
          <p class="text-gray-500 text-sm">Created {{ formatDate(task.created_at) }}</p>
        </div>

        <!-- Actions based on state -->
        <div class="flex gap-2 flex-wrap justify-end">
          <UButton icon="i-heroicons-arrow-path" color="gray" variant="soft" :loading="pending" @click="refresh()" />

          <!-- State: created -->
          <template v-if="task.status === 'created'">
            <UButton v-if="isQuote"
              icon="i-heroicons-chat-bubble-left-right" color="primary"
              @click="isSubmitResponseOpen = true">
              Submit Response
            </UButton>
            <UButton v-if="isSolicitation"
              icon="i-heroicons-check" color="green" variant="soft"
              :loading="submitting" @click="confirmDelivery">
              Confirm Delivery
            </UButton>
          </template>

          <!-- State: draft -->
          <UButton v-if="task.status === 'draft'"
            icon="i-heroicons-check-circle" color="blue" variant="soft"
            :loading="submitting" @click="approveSubmission">
            Approve
          </UButton>

          <!-- State: approved -->
          <UButton v-if="task.status === 'approved'"
            icon="i-heroicons-check-badge" color="green"
            :loading="submitting" @click="completeTask">
            Complete
          </UButton>

          <!-- State: completed - no actions -->
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Task Info -->
        <UCard>
          <template #header><p class="font-semibold text-slate-700">Task Info</p></template>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between"><span class="text-gray-500">Task ID</span><span class="font-mono text-xs">{{ task.id }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Application ID</span><span class="font-mono text-xs">{{ task.application_id }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Provider ID</span><span class="font-mono text-xs">{{ task.task_info?.provider_id }}</span></div>
            <div v-if="task.task_info?.provider_name" class="flex justify-between"><span class="text-gray-500">Provider</span><span>{{ task.task_info.provider_name }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Org</span><span class="font-mono text-xs">{{ task.org_id }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Created</span><span>{{ formatDate(task.created_at) }}</span></div>
            <div class="flex justify-between"><span class="text-gray-500">Updated</span><span>{{ formatDate(task.updated_at) }}</span></div>
          </div>
        </UCard>

        <!-- Task Info Details -->
        <UCard>
          <template #header><p class="font-semibold text-slate-700">Request Details</p></template>
          <div class="space-y-4 text-sm">
            <div v-if="task.task_info">
              <pre class="text-xs bg-gray-50 p-3 rounded overflow-x-auto">{{ JSON.stringify(task.task_info, null, 2) }}</pre>
            </div>
            <div v-else class="text-gray-400 text-center py-4">No task info</div>
          </div>
        </UCard>
      </div>

      <!-- Submission -->
      <UCard v-if="task.submission">
        <template #header><p class="font-semibold text-slate-700">Submission</p></template>
        <pre class="text-xs bg-gray-50 p-3 rounded overflow-x-auto">{{ JSON.stringify(task.submission, null, 2) }}</pre>
      </UCard>

      <!-- Attachments -->
      <UCard v-if="task.attachments?.length">
        <template #header><p class="font-semibold text-slate-700">Attachments</p></template>
        <div class="space-y-2">
          <div v-for="(url, i) in task.attachments" :key="i" class="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
            <UIcon name="i-heroicons-document" class="w-5 h-5 text-gray-400 flex-shrink-0" />
            <a :href="url" target="_blank" class="text-sm text-blue-600 hover:underline truncate font-mono">{{ url }}</a>
          </div>
        </div>
      </UCard>
    </template>

    <!-- Submit Response Slideover (Quote) -->
    <USlideover v-model:open="isSubmitResponseOpen" side="right">
      <template #content>
        <div class="flex flex-col h-full">
          <div class="flex justify-between items-center p-6 border-b">
            <div><h2 class="text-lg font-semibold text-slate-900">Submit Quote Response</h2></div>
            <UButton icon="i-heroicons-x-mark" color="gray" variant="ghost" @click="isSubmitResponseOpen = false" />
          </div>
          <div class="flex-1 overflow-y-auto p-6 space-y-6">
            <div class="grid grid-cols-2 gap-4">
              <UFormField label="Quote ID" required>
                <UInput v-model="quoteForm.quote_id" placeholder="QUOTE-001" class="w-full" />
              </UFormField>
              <UFormField label="Valid Until" required>
                <UInput v-model="quoteForm.valid_until" type="date" class="w-full" />
              </UFormField>
            </div>
            <UFormField label="Responded By" required>
              <UInput v-model="quoteForm.recorded_by" placeholder="Your name" class="w-full" />
            </UFormField>
            <UFormField label="Document URL">
              <UInput v-model="quoteForm.document_url" placeholder="https://..." class="w-full" />
            </UFormField>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <p class="font-medium text-sm text-slate-700">Plans</p>
                <UButton icon="i-heroicons-plus" size="xs" color="gray" variant="soft" @click="addPlan">Add</UButton>
              </div>
              <div v-for="(plan, i) in quoteForm.plans" :key="i" class="border rounded-lg p-4 space-y-3">
                <div class="flex justify-between items-center">
                  <p class="text-sm font-semibold text-slate-700">Plan {{ i + 1 }}</p>
                  <UButton v-if="quoteForm.plans.length > 1" icon="i-heroicons-trash" size="xs" color="red" variant="ghost" @click="removePlan(i)" />
                </div>
                <div class="grid grid-cols-2 gap-3">
                  <UFormField label="Plan ID"><UInput v-model="plan.plan_id" placeholder="PLAN-001" class="w-full" /></UFormField>
                  <UFormField label="Name"><UInput v-model="plan.name" placeholder="Basic" class="w-full" /></UFormField>
                  <UFormField label="Premium"><UInput v-model="plan.premium" type="number" placeholder="1000" class="w-full" /></UFormField>
                </div>
                <UFormField label="Coverage Details">
                  <div class="space-y-2">
                    <div v-for="(value, key) in plan.coverage_details" :key="key" class="flex gap-2 items-center">
                      <span class="text-sm font-medium text-gray-600 w-24 truncate">{{ key }}:</span>
                      <UInput v-model="plan.coverage_details[key]" placeholder="Value" class="flex-1" />
                      <UButton icon="i-heroicons-trash" size="xs" color="red" variant="ghost" @click="delete plan.coverage_details[key]" />
                    </div>
                    <div class="flex gap-2">
                      <UInput v-model="newCoverageKey" placeholder="Key (e.g., liability)" class="flex-1" @keydown.enter="addCoverageDetail(plan)" />
                      <UInput v-model="newCoverageValue" placeholder="Value" class="flex-1" @keydown.enter="addCoverageDetail(plan)" />
                      <UButton size="xs" color="gray" variant="soft" @click="addCoverageDetail(plan)">Add</UButton>
                    </div>
                  </div>
                </UFormField>
              </div>
            </div>
          </div>
          <div class="p-6 border-t flex justify-end gap-3">
            <UButton color="gray" variant="soft" @click="isSubmitResponseOpen = false">Cancel</UButton>
            <UButton color="primary" icon="i-heroicons-paper-airplane" :loading="submitting" @click="submitResponse">
              Submit
            </UButton>
          </div>
        </div>
      </template>
    </USlideover>
  </div>
</template>