<script lang="ts" setup>
import { Link, router } from '@inertiajs/vue3'
import { computed, ref, watch } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import type { OrderRiskAssessment, PaginatedResponse, StatusColor } from '@/types'

interface Props {
  assessments: PaginatedResponse<OrderRiskAssessment>
  filters: {
    risk_level: string
    action: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const riskLevelFilter = ref<string>(props.filters.risk_level)
const actionFilter = ref<string>(props.filters.action)

function resolveRiskColor(level: string): StatusColor {
  const map: Record<string, StatusColor> = {
    low: 'success',
    medium: 'warning',
    high: 'error',
    critical: 'error',
  }
  return map[level] ?? 'secondary'
}

function resolveActionColor(action: string): StatusColor {
  const map: Record<string, StatusColor> = {
    approve: 'success',
    hold: 'warning',
    reject: 'error',
  }
  return map[action] ?? 'secondary'
}

function riskScoreColor(score: number): string {
  if (score >= 85) return 'error'
  if (score >= 60) return 'warning'
  if (score >= 30) return 'info'
  return 'success'
}

const tableHeaders = computed(() => [
  { title: 'Order', key: 'order', sortable: false },
  { title: 'Customer', key: 'user', sortable: false },
  { title: 'Risk Score', key: 'risk_score', sortable: true, align: 'center' as const },
  { title: 'Risk Level', key: 'risk_level', sortable: true, align: 'center' as const },
  { title: 'Auto Action', key: 'auto_action', sortable: true, align: 'center' as const },
  { title: 'Date', key: 'created_at', sortable: true },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
])

function applyFilters(): void {
  router.get('/fraud-queue', {
    risk_level: riskLevelFilter.value !== 'all' ? riskLevelFilter.value : undefined,
    action: actionFilter.value !== 'all' ? actionFilter.value : undefined,
  }, {
    preserveState: true,
    replace: true,
  })
}

watch([riskLevelFilter, actionFilter], applyFilters)

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}

function approveAssessment(id: number): void {
  router.post(`/fraud-queue/${id}/approve`, {}, { preserveScroll: true })
}

function rejectAssessment(id: number): void {
  if (confirm('Are you sure you want to reject this order? It will be cancelled.')) {
    router.post(`/fraud-queue/${id}/reject`, {}, { preserveScroll: true })
  }
}
</script>

<template>
  <div>
    <div class="text-h4 font-weight-bold mb-2">
      Fraud Queue
    </div>
    <div class="text-body-2 text-medium-emphasis mb-6">
      Review orders flagged by fraud detection
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="6">
            <VSelect
              v-model="riskLevelFilter"
              :items="[
                { title: 'All Levels', value: 'all' },
                { title: 'Low', value: 'low' },
                { title: 'Medium', value: 'medium' },
                { title: 'High', value: 'high' },
                { title: 'Critical', value: 'critical' },
              ]"
              label="Risk Level"
              variant="outlined"
              density="comfortable"
              hide-details
            />
          </VCol>
          <VCol cols="12" md="6">
            <VSelect
              v-model="actionFilter"
              :items="[
                { title: 'All Actions', value: 'all' },
                { title: 'Hold', value: 'hold' },
                { title: 'Reject', value: 'reject' },
              ]"
              label="Auto Action"
              variant="outlined"
              density="comfortable"
              hide-details
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="assessments.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <template #item.order="{ item }">
          <span v-if="item.order" class="font-weight-medium">
            {{ item.order.order_number }}
          </span>
          <span v-else class="text-medium-emphasis">No order</span>
        </template>

        <template #item.user="{ item }">
          <div v-if="item.user">
            <div class="font-weight-medium">
              {{ item.user.name }}
            </div>
            <div class="text-body-2 text-medium-emphasis">
              {{ item.user.email }}
            </div>
          </div>
        </template>

        <template #item.risk_score="{ item }">
          <VProgressLinear
            :model-value="item.risk_score"
            :color="riskScoreColor(item.risk_score)"
            height="20"
            rounded
            class="mx-auto"
            style="max-width: 120px;"
          >
            <template #default>
              <span class="text-caption font-weight-bold">{{ item.risk_score }}</span>
            </template>
          </VProgressLinear>
        </template>

        <template #item.risk_level="{ item }">
          <VChip
            :color="resolveRiskColor(item.risk_level)"
            size="small"
            class="text-capitalize"
          >
            {{ item.risk_level }}
          </VChip>
        </template>

        <template #item.auto_action="{ item }">
          <VChip
            :color="resolveActionColor(item.auto_action)"
            size="small"
            variant="tonal"
            class="text-capitalize"
          >
            {{ item.auto_action }}
          </VChip>
        </template>

        <template #item.created_at="{ item }">
          {{ formatDate(item.created_at) }}
        </template>

        <template #item.actions="{ item }">
          <div class="d-flex gap-1 justify-center">
            <Link :href="`/fraud-queue/${item.id}`" class="text-decoration-none">
              <VBtn icon="tabler-eye" variant="text" size="small" />
            </Link>
            <VBtn
              icon="tabler-check"
              variant="text"
              size="small"
              color="success"
              @click="approveAssessment(item.id)"
            />
            <VBtn
              icon="tabler-x"
              variant="text"
              size="small"
              color="error"
              @click="rejectAssessment(item.id)"
            />
          </div>
        </template>

        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-shield-check" size="48" color="success" class="mb-2" />
            <div class="text-medium-emphasis">
              No flagged orders in the queue.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
