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

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

const payload = computed(() => data.value?.payload)

const isSolicitation = computed(() => task.value?.comm_type === 'solicitation')
const isQuote        = computed(() => task.value?.comm_type === 'quote')

// ── Respond (quote) ──────────────────────────────────────────────────────────
const isRespondOpen = ref(false)
const submitting    = ref(false)
const toast         = useToast()
const { $tasks } = useNuxtApp()

const plans = ref([{ name: '', premium: '', coverage_details: '', deductible: '', coverage_limit: '' }])
const respondForm = ref({ valid_until: '', entered_by: '' })

function addPlan() { plans.value.push({ name: '', premium: '', coverage_details: '', deductible: '', coverage_limit: '' }) }
function removePlan(i: number) { plans.value.splice(i, 1) }

async function submitResponse() {
  submitting.value = true
  try {
    await $tasks(`/tasks/${id}/respond`, {
      method: 'POST',
      body: {
        valid_until: respondForm.value.valid_until,
        entered_by:  respondForm.value.entered_by,
        plans: plans.value.map(p => ({
          name: p.name, premium: parseFloat(p.premium), coverage_details: p.coverage_details,
          deductible: p.deductible ? parseFloat(p.deductible) : 0,
          coverage_limit: p.coverage_limit ? parseFloat(p.coverage_limit) : 0
        }))
      }
    })
    toast.add({ title: 'Response submitted', color: 'green' })
    isRespondOpen.value = false
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally { submitting.value = false }
}

const isRespondFormValid = computed(() =>
  respondForm.value.valid_until && respondForm.value.entered_by &&
  plans.value.every(p => p.name && p.premium && p.coverage_details)
)

// ── Confirm delivery (solicitation) ─────────────────────────────────────────
const confirmingDelivery = ref(false)

async function confirmDelivery() {
  confirmingDelivery.value = true
  try {
    await $tasks(`/tasks/${id}/confirm-delivery`, { 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 { confirmingDelivery.value = false }
}

// ── Issue policy (solicitation) ──────────────────────────────────────────────
const isIssueOpen = ref(false)
const issuing     = ref(false)
const issueForm   = ref({ policy_number: '', effective_date: '', expiry_date: '' })

const isIssueFormValid = computed(() =>
  issueForm.value.policy_number && issueForm.value.effective_date && issueForm.value.expiry_date
)

async function submitIssuePolicy() {
  issuing.value = true
  try {
    await $task(`/tasks/${id}/issue-policy`, { method: 'POST', body: issueForm.value })
    toast.add({ title: 'Policy issued successfully', color: 'green' })
    isIssueOpen.value = false
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally { issuing.value = false }
}

// ── Solicitation PDF ─────────────────────────────────────────────────────────
const pdfUrl     = computed(() => task.value?.download_url ?? null)
const showPdf    = ref(false)

// ── Helpers ──────────────────────────────────────────────────────────────────
const statusColor = (s: string) =>
  ({ pending: 'yellow', responded: 'blue', delivered: 'purple', issued: 'green' }[s] ?? '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="/tasks">
      <UButton icon="i-heroicons-arrow-left" color="gray" variant="ghost">Back to Tasks</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="blue" variant="outline">{{ task.policy_type?.toUpperCase() }}</UBadge>
            <UBadge color="gray" variant="outline">{{ task.comm_type }}</UBadge>
          </div>
          <h1 class="text-xl font-bold text-slate-900 font-mono">{{ task.application_id }}</h1>
          <p class="text-gray-500 text-sm">Received {{ formatDate(task.created_at) }}</p>
        </div>

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

          <!-- Quote actions -->
          <UButton v-if="isQuote && task.status === 'pending'"
            icon="i-heroicons-chat-bubble-left-right" color="primary" @click="isRespondOpen = true">
            Record Response
          </UButton>

          <!-- Solicitation actions -->
          <template v-if="isSolicitation">
            <UButton v-if="task.status === 'pending'"
              icon="i-heroicons-check" color="green" variant="soft"
              :loading="confirmingDelivery" @click="confirmDelivery">
              Confirm Delivery
            </UButton>
            <UButton v-if="task.status === 'delivered'"
              icon="i-heroicons-document-check" color="primary" @click="isIssueOpen = true">
              Issue Policy
            </UButton>
          </template>
        </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.provider_id }}</span></div>
            <div v-if="task.provider_name" class="flex justify-between"><span class="text-gray-500">Provider</span><span>{{ task.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>

        <!-- Payload -->
        <UCard>
          <template #header><p class="font-semibold text-slate-700">Request Payload</p></template>
          <div class="space-y-4 text-sm">
            <div v-if="payload?.applicant_info">
              <p class="text-xs font-semibold text-gray-400 uppercase mb-2">Applicant</p>
              <div class="bg-gray-50 rounded-lg p-3 space-y-1.5">
                <div class="flex justify-between"><span class="text-gray-500">Name</span><span>{{ payload.applicant_info.name }}</span></div>
                <div class="flex justify-between"><span class="text-gray-500">DOB</span><span>{{ payload.applicant_info.date_of_birth }}</span></div>
                <div class="flex justify-between"><span class="text-gray-500">Document</span><span class="font-mono text-xs">{{ payload.applicant_info.document_id }}</span></div>
              </div>
            </div>
            <div v-if="payload?.car_details">
              <p class="text-xs font-semibold text-gray-400 uppercase mb-2">Vehicle</p>
              <div class="bg-gray-50 rounded-lg p-3 space-y-1.5">
                <div class="flex justify-between"><span class="text-gray-500">Plate</span><span class="font-mono font-medium">{{ payload.car_details.plate }}</span></div>
                <div class="flex justify-between"><span class="text-gray-500">Vehicle</span><span>{{ payload.car_details.year }} {{ payload.car_details.make }} {{ payload.car_details.model }}</span></div>
                <div class="flex justify-between"><span class="text-gray-500">Value</span><span>${{ Number(payload.car_details.car_value).toLocaleString() }}</span></div>
              </div>
            </div>
          </div>
        </UCard>
      </div>

      <!-- Solicitation PDF section -->
      <UCard v-if="isSolicitation">
        <template #header>
          <div class="flex justify-between items-center">
            <p class="font-semibold text-slate-700 flex items-center gap-2">
              <UIcon name="i-heroicons-document-text" class="w-4 h-4" /> Solicitation Document
            </p>
            <div class="flex gap-2">
              <UButton v-if="pdfUrl" icon="i-heroicons-eye" color="gray" variant="soft" size="xs"
                @click="showPdf = !showPdf">{{ showPdf ? 'Hide' : 'Preview' }}</UButton>
              <UButton v-if="pdfUrl" icon="i-heroicons-arrow-top-right-on-square"
                color="gray" variant="soft" size="xs" :to="pdfUrl" target="_blank">Open</UButton>
            </div>
          </div>
        </template>

        <div v-if="!pdfUrl" class="text-center py-10 text-gray-400">
          <UIcon name="i-heroicons-document" class="w-10 h-10 mx-auto mb-2" />
          <p class="text-sm">No solicitation document available</p>
        </div>

        <div v-else-if="showPdf">
          <iframe :src="pdfUrl" class="w-full rounded-lg border" style="height: 600px;" />
        </div>

        <div v-else class="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
          <UIcon name="i-heroicons-document-text" class="w-8 h-8 text-red-400 flex-shrink-0" />
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-slate-800">Solicitation v{{ task.version ?? 1 }}</p>
            <p class="text-xs text-gray-400 font-mono truncate">{{ task.s3_key }}</p>
          </div>
          <UBadge :color="statusColor(task.status)" variant="soft" size="sm">{{ task.status }}</UBadge>
        </div>
      </UCard>
    </template>

    <!-- Quote respond slideover -->
    <USlideover v-model:open="isRespondOpen" 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">Record Quote Response</h2></div>
            <UButton icon="i-heroicons-x-mark" color="gray" variant="ghost" @click="isRespondOpen = false" />
          </div>
          <div class="flex-1 overflow-y-auto p-6 space-y-6">
            <div class="grid grid-cols-2 gap-4">
              <UFormField label="Valid Until" required>
                <UInput v-model="respondForm.valid_until" type="date" class="w-full" />
              </UFormField>
              <UFormField label="Entered By" required>
                <UInput v-model="respondForm.entered_by" placeholder="Your name" class="w-full" />
              </UFormField>
            </div>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <p class="font-medium text-sm text-slate-700">Plans <UBadge color="gray" variant="soft" size="xs" class="ml-1">{{ plans.length }}</UBadge></p>
                <UButton icon="i-heroicons-plus" size="xs" color="gray" variant="soft" @click="addPlan">Add Plan</UButton>
              </div>
              <div v-for="(plan, i) in 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="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="Name" required><UInput v-model="plan.name" placeholder="Basic / Standard / Premium" class="w-full" /></UFormField>
                  <UFormField label="Premium (USD)" required><UInput v-model="plan.premium" type="number" class="w-full" /></UFormField>
                  <UFormField label="Deductible"><UInput v-model="plan.deductible" type="number" class="w-full" /></UFormField>
                  <UFormField label="Coverage Limit"><UInput v-model="plan.coverage_limit" type="number" class="w-full" /></UFormField>
                </div>
                <UFormField label="Coverage Details" required>
                  <UTextarea v-model="plan.coverage_details" :rows="2" class="w-full" />
                </UFormField>
              </div>
            </div>
          </div>
          <div class="p-6 border-t flex justify-end gap-3">
            <UButton color="gray" variant="soft" @click="isRespondOpen = false">Cancel</UButton>
            <UButton color="primary" icon="i-heroicons-paper-airplane" :loading="submitting" :disabled="!isRespondFormValid" @click="submitResponse">
              Submit Response
            </UButton>
          </div>
        </div>
      </template>
    </USlideover>

    <!-- Issue policy slideover -->
    <USlideover v-model:open="isIssueOpen" 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">Issue Policy</h2>
              <p class="text-sm text-gray-500">Enter the policy details from the provider</p>
            </div>
            <UButton icon="i-heroicons-x-mark" color="gray" variant="ghost" @click="isIssueOpen = false" />
          </div>
          <div class="flex-1 p-6 space-y-4">
            <UFormField label="Policy Number" required>
              <UInput v-model="issueForm.policy_number" placeholder="POL-2026-001" class="w-full" />
            </UFormField>
            <UFormField label="Effective Date" required>
              <UInput v-model="issueForm.effective_date" type="date" class="w-full" />
            </UFormField>
            <UFormField label="Expiry Date" required>
              <UInput v-model="issueForm.expiry_date" type="date" class="w-full" />
            </UFormField>
          </div>
          <div class="p-6 border-t flex justify-end gap-3">
            <UButton color="gray" variant="soft" @click="isIssueOpen = false">Cancel</UButton>
            <UButton color="primary" icon="i-heroicons-document-check" :loading="issuing" :disabled="!isIssueFormValid" @click="submitIssuePolicy">
              Issue Policy
            </UButton>
          </div>
        </div>
      </template>
    </USlideover>
  </div>
</template>
