<script setup lang="ts">
import NestedJsonViewer from '~/components/back-office/NestedJsonViewer.vue'

const route = useRoute()
const id = decodeURIComponent(route.params.id as string)

usePageTitle(`Task: ${id}`)

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')

const { $document } = useNuxtApp()

async function downloadDocument(documentId: string) {
  try {
    const response = await $document(`/documents/${documentId}/download-url`, {
      method: 'GET'
    })
    if (response.data?.download_url) {
      window.open(response.data.download_url, '_blank')
    }
  } catch (e) {
    toast.add({ title: 'Failed to get document URL', description: String(e), color: 'red' })
  }
}

// State-based actions
const isSubmitResponseOpen = ref(false)
const isSolicitationSubmitOpen = 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: '',
  documents: [] as Array<{ document_id: string; filename: string }>,
  plans: [{ plan_id: '', name: '', premium: '', coverage_details: {} as Record<string, string> }]
})

// Solicitation response form
const solicitationForm = ref({
  provider_policy_number: '',
  effective_date: '',
  expiry_date: ''
})

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('')

// File upload handling
const uploading = ref(false)

async function uploadFile(file: File): Promise<{ document_id: string; filename: string }> {
  const formData = new FormData()
  formData.append('file', file)
  const response = await $document('/api/documents/upload', {
    method: 'POST',
    body: formData
  })
  return {
    document_id: response.data.document_id,
    filename: file.name
  }
}

async function handleFilesSelected(event: Event) {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (!files || files.length === 0) return

  uploading.value = true
  try {
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      const doc = await uploadFile(file)
      quoteForm.value.documents.push(doc)
    }
  } catch (e: any) {
    toast.add({ title: 'Upload failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    uploading.value = false
    // Reset file input
    target.value = ''
  }
}

function removeDocument(documentId: string) {
  quoteForm.value.documents = quoteForm.value.documents.filter(d => d.document_id !== documentId)
}

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,
        documents: quoteForm.value.documents.map(d => d.document_id),
        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
    // Reset form
    quoteForm.value = {
      quote_id: '',
      valid_until: '',
      recorded_by: '',
      documents: [],
      plans: [{ plan_id: '', name: '', premium: '', coverage_details: {} }]
    }
    await refresh()
  } catch (e: any) {
    toast.add({ title: 'Failed', description: e?.data?.error ?? e.message, color: 'red' })
  } finally {
    submitting.value = false
  }
}

function openSolicitationModal() {
  solicitationForm.value = {
    provider_policy_number: '',
    effective_date: '',
    expiry_date: ''
  }
  isSolicitationSubmitOpen.value = true
}

async function submitSolicitation() {
  if (!solicitationForm.value.provider_policy_number ||
      !solicitationForm.value.effective_date ||
      !solicitationForm.value.expiry_date) {
    toast.add({ title: 'Please fill all required fields', color: 'red' })
    return
  }

  submitting.value = true
  try {
    await $workload(`/tasks/${id}/submit`, {
      method: 'POST',
      body: {
        provider_policy_number: solicitationForm.value.provider_policy_number,
        effective_date: solicitationForm.value.effective_date,
        expiry_date: solicitationForm.value.expiry_date
      }
    })
    toast.add({ title: 'Response submitted', color: 'green' })
    isSolicitationSubmitOpen.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 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="/back-office/workload">
      <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="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-chat-bubble-left-right"
              color="primary"
              @click="openSolicitationModal">
              Submit Response
            </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-3 gap-6">
        <!-- Task Info Sidebar (1/3 width) -->
        <div class="md:col-span-1">
          <UCard class="sticky top-6">
            <template #header><p class="font-semibold text-slate-700 text-sm">Task Info</p></template>
            <div class="space-y-2 text-sm">
              <div class="flex justify-between"><span class="text-gray-500 text-xs">Task ID</span><span class="font-mono text-xs">{{ task.id }}</span></div>
              <div class="flex justify-between"><span class="text-gray-500 text-xs">Application ID</span><span class="font-mono text-xs">{{ task.application_id }}</span></div>
              <div class="flex justify-between"><span class="text-gray-500 text-xs">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 text-xs">Provider</span><span class="text-xs">{{ task.task_info.provider_name }}</span></div>
              <div class="flex justify-between"><span class="text-gray-500 text-xs">Org</span><span class="font-mono text-xs">{{ task.org_id }}</span></div>
              <div class="flex justify-between"><span class="text-gray-500 text-xs">Created</span><span class="text-xs">{{ formatDate(task.created_at) }}</span></div>
              <div class="flex justify-between"><span class="text-gray-500 text-xs">Updated</span><span class="text-xs">{{ formatDate(task.updated_at) }}</span></div>
              <div class="flex justify-between pt-2 border-t">
                <span class="text-gray-500 text-xs">Status</span>
                <UBadge :color="statusColor(task.status)" variant="soft" size="xs">{{ task.status }}</UBadge>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-500 text-xs">Policy Type</span>
                <UBadge :color="policyTypeColor(task.task_info?.policy_type)" variant="outline" size="xs">{{ task.task_info?.policy_type?.toUpperCase() || '—' }}</UBadge>
              </div>
            </div>
          </UCard>
        </div>

        <!-- Request Details Main (2/3 width) -->
        <div class="md:col-span-2 space-y-6">
          <UCard>
            <template #header><p class="font-semibold text-slate-700 text-sm">Request Details</p></template>
            <div v-if="task.task_info">
              <NestedJsonViewer :data="task.task_info" />
            </div>
            <div v-else class="text-gray-400 text-center py-4">No task info available</div>
          </UCard>

          <!-- Submission -->
          <UCard v-if="task.submission">
            <template #header><p class="font-semibold text-slate-700 text-sm">Response</p></template>
            <div class="space-y-4 text-sm">
              <div class="grid grid-cols-2 gap-4">
                <div v-if="task.submission.quote_id" class="flex justify-between border-b pb-2">
                  <span class="text-gray-500">Quote ID</span>
                  <span class="font-mono text-xs">{{ task.submission.quote_id }}</span>
                </div>
                <div v-if="task.submission.valid_until" class="flex justify-between border-b pb-2">
                  <span class="text-gray-500">Valid Until</span>
                  <span class="text-xs">{{ task.submission.valid_until }}</span>
                </div>
                <div v-if="task.submission.recorded_by" class="flex justify-between border-b pb-2">
                  <span class="text-gray-500">Recorded By</span>
                  <span class="text-xs">{{ task.submission.recorded_by }}</span>
                </div>
              </div>
              <div v-if="task.submission.documents?.length" class="border-t pt-4">
                <div class="text-xs font-medium text-gray-500 mb-2">Documents</div>
                <div class="space-y-2">
                  <div v-for="(doc, i) in task.submission.documents" :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" />
                    <div class="flex-1 min-w-0">
                      <div class="text-sm font-medium text-gray-900 truncate">{{ doc.filename || 'Document' }}</div>
                      <div class="text-xs text-gray-500 truncate font-mono">{{ doc.document_id }}</div>
                    </div>
                    <UButton icon="i-heroicons-arrow-down" size="xs" color="gray" variant="ghost" :loading="false" @click="downloadDocument(doc.document_id)" />
                  </div>
                </div>
              </div>
              <div v-if="task.submission.plans?.length" class="border-t pt-4">
                <div class="text-xs font-medium text-gray-500 mb-2">Plans</div>
                <div class="space-y-3">
                  <div v-for="(plan, i) in task.submission.plans" :key="i" class="border rounded-lg p-3">
                    <div class="grid grid-cols-2 gap-2 mb-2">
                      <div><span class="text-xs text-gray-500">Plan ID</span><div class="font-mono text-xs">{{ plan.plan_id }}</div></div>
                      <div><span class="text-xs text-gray-500">Name</span><div class="text-xs">{{ plan.name }}</div></div>
                      <div><span class="text-xs text-gray-500">Premium</span><div class="text-sm font-semibold text-green-600">${{ plan.premium }}</div></div>
                    </div>
                    <div v-if="plan.coverage_details && Object.keys(plan.coverage_details).length" class="border-t pt-2 mt-2">
                      <div class="text-xs text-gray-500 mb-1">Coverage Details</div>
                      <div class="grid grid-cols-2 gap-1 text-xs">
                        <div v-for="(value, key) in plan.coverage_details" :key="key" class="flex justify-between">
                          <span class="text-gray-600 capitalize">{{ key.replace(/_/g, ' ') }}:</span>
                          <span class="font-medium">{{ value }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </UCard>

          <!-- Attachments -->
          <UCard v-if="task.attachments?.length">
            <template #header><p class="font-semibold text-slate-700 text-sm">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 flex-1">{{ url }}</a>
                <UButton icon="i-heroicons-arrow-down" size="xs" color="gray" variant="ghost" />
              </div>
            </div>
          </UCard>
        </div>
      </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="Documents">
              <div class="space-y-3">
                <UFileUpload
                  multiple
                  @change="handleFilesSelected"
                  :disabled="uploading"
                  class="w-full"
                />
                <div v-if="quoteForm.documents.length" class="space-y-2">
                  <div v-for="doc in quoteForm.documents" :key="doc.document_id" 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" />
                    <div class="flex-1 min-w-0">
                      <div class="text-sm font-medium text-gray-900 truncate">{{ doc.filename }}</div>
                      <div class="text-xs text-gray-500 truncate font-mono">{{ doc.document_id }}</div>
                    </div>
                    <UButton icon="i-heroicons-x-mark" size="xs" color="red" variant="ghost" @click="removeDocument(doc.document_id)" />
                  </div>
                </div>
              </div>
            </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" :disabled="!quoteForm.quote_id || !quoteForm.valid_until || !quoteForm.recorded_by || quoteForm.plans.length === 0 || quoteForm.plans.some(p => !p.name || !p.premium || Object.keys(p.coverage_details || {}).length === 0)" @click="submitResponse">
              Submit
            </UButton>
          </div>
        </div>
        </template>
      </USlideover>

      <!-- Submit Response Slideover (Solicitation) -->
      <USlideover v-model:open="isSolicitationSubmitOpen" 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 Response</h2></div>
              <UButton icon="i-heroicons-x-mark" color="gray" variant="ghost" @click="isSolicitationSubmitOpen = false" />
            </div>
            <div class="flex-1 overflow-y-auto p-6 space-y-6">
              <UFormField label="Provider Policy Number" required>
                <UInput v-model="solicitationForm.provider_policy_number" placeholder="e.g., POL-2024-001" class="w-full" />
              </UFormField>
              <UFormField label="Effective Date" required>
                <UInput v-model="solicitationForm.effective_date" type="date" class="w-full" />
              </UFormField>
              <UFormField label="Expiry Date" required>
                <UInput v-model="solicitationForm.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="isSolicitationSubmitOpen = false">Cancel</UButton>
              <UButton color="primary" icon="i-heroicons-paper-airplane" :loading="submitting" :disabled="!solicitationForm.provider_policy_number || !solicitationForm.effective_date || !solicitationForm.expiry_date" @click="submitSolicitation">
                Submit
              </UButton>
            </div>
          </div>
        </template>
      </USlideover>
  </div>
</template>
