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

interface Props {
  assessment: OrderRiskAssessment
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

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

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

function checkScoreColor(score: number): string {
  if (score >= 80) return 'error'
  if (score >= 50) return 'warning'
  if (score > 0) return 'info'
  return 'success'
}

const checkLabels: Record<string, string> = {
  disposable_email: 'Disposable Email Check',
  velocity: 'Signup Velocity Check',
  ip_country_mismatch: 'IP/Country Mismatch',
  email_domain_age: 'Email Domain MX Check',
  previous_flags: 'Previous Fraud Flags',
}

const checkWeights: Record<string, number> = {
  disposable_email: 25,
  velocity: 20,
  ip_country_mismatch: 20,
  email_domain_age: 15,
  previous_flags: 20,
}

const isReviewed = computed<boolean>(() => props.assessment.reviewed_at !== null)

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

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

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

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Risk Assessment #{{ assessment.id }}
        </div>
        <div class="text-body-2 text-medium-emphasis">
          {{ assessment.order ? `Order: ${assessment.order.order_number}` : 'No associated order' }}
          &mdash; Created {{ formatDate(assessment.created_at) }}
        </div>
      </div>
      <div v-if="!isReviewed" class="d-flex gap-2">
        <VBtn
          color="success"
          prepend-icon="tabler-check"
          @click="approveAssessment"
        >
          Approve
        </VBtn>
        <VBtn
          color="error"
          variant="outlined"
          prepend-icon="tabler-x"
          @click="rejectAssessment"
        >
          Reject
        </VBtn>
      </div>
      <VChip v-else color="info" variant="tonal">
        Reviewed by {{ assessment.reviewer?.name ?? 'Unknown' }}
        on {{ formatDate(assessment.reviewed_at!) }}
      </VChip>
    </div>

    <VRow>
      <!-- Overall Score -->
      <VCol cols="12" md="4">
        <VCard class="h-100">
          <VCardTitle>Overall Risk Score</VCardTitle>
          <VCardText class="text-center">
            <div class="d-flex justify-center mb-4">
              <VProgressCircular
                :model-value="assessment.risk_score"
                :color="riskScoreColor(assessment.risk_score)"
                :size="140"
                :width="12"
              >
                <span class="text-h3 font-weight-bold">{{ assessment.risk_score }}</span>
              </VProgressCircular>
            </div>
            <VChip
              :color="resolveRiskColor(assessment.risk_level)"
              size="large"
              class="text-capitalize"
            >
              {{ assessment.risk_level }}
            </VChip>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Customer Info -->
      <VCol cols="12" md="4">
        <VCard class="h-100">
          <VCardTitle>Customer Information</VCardTitle>
          <VCardText>
            <VList density="compact">
              <VListItem>
                <template #prepend>
                  <VIcon icon="tabler-user" class="me-2" />
                </template>
                <VListItemTitle>{{ assessment.user?.name ?? 'Unknown' }}</VListItemTitle>
                <VListItemSubtitle>{{ assessment.user?.email }}</VListItemSubtitle>
              </VListItem>
              <VListItem v-if="assessment.user?.status">
                <template #prepend>
                  <VIcon icon="tabler-circle-check" class="me-2" />
                </template>
                <VListItemTitle class="text-capitalize">
                  {{ assessment.user.status }}
                </VListItemTitle>
                <VListItemSubtitle>Account Status</VListItemSubtitle>
              </VListItem>
              <VListItem v-if="assessment.user?.created_at">
                <template #prepend>
                  <VIcon icon="tabler-calendar" class="me-2" />
                </template>
                <VListItemTitle>{{ formatDate(assessment.user.created_at) }}</VListItemTitle>
                <VListItemSubtitle>Account Created</VListItemSubtitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Order Info -->
      <VCol cols="12" md="4">
        <VCard class="h-100">
          <VCardTitle>Order Information</VCardTitle>
          <VCardText>
            <template v-if="assessment.order">
              <VList density="compact">
                <VListItem>
                  <template #prepend>
                    <VIcon icon="tabler-hash" class="me-2" />
                  </template>
                  <VListItemTitle>{{ assessment.order.order_number }}</VListItemTitle>
                  <VListItemSubtitle>Order Number</VListItemSubtitle>
                </VListItem>
                <VListItem>
                  <template #prepend>
                    <VIcon icon="tabler-cash" class="me-2" />
                  </template>
                  <VListItemTitle>${{ parseFloat(assessment.order.total).toFixed(2) }} {{ assessment.order.currency }}</VListItemTitle>
                  <VListItemSubtitle>Total</VListItemSubtitle>
                </VListItem>
                <VListItem>
                  <template #prepend>
                    <VIcon icon="tabler-circle-check" class="me-2" />
                  </template>
                  <VListItemTitle class="text-capitalize">
                    {{ assessment.order.status }}
                  </VListItemTitle>
                  <VListItemSubtitle>Order Status</VListItemSubtitle>
                </VListItem>
              </VList>
            </template>
            <div v-else class="text-center text-medium-emphasis py-4">
              No associated order
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Individual Checks -->
    <VCard class="mt-6">
      <VCardTitle>Risk Check Breakdown</VCardTitle>
      <VCardText>
        <VTable>
          <thead>
            <tr>
              <th>Check</th>
              <th class="text-center">
                Weight
              </th>
              <th class="text-center">
                Score
              </th>
              <th class="text-center">
                Weighted
              </th>
              <th>Details</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(check, key) in assessment.checks" :key="key">
              <td class="font-weight-medium">
                {{ checkLabels[key as string] ?? key }}
              </td>
              <td class="text-center">
                {{ checkWeights[key as string] ?? 0 }}%
              </td>
              <td class="text-center">
                <VChip
                  :color="checkScoreColor(check.score)"
                  size="small"
                  variant="tonal"
                >
                  {{ check.score }}/100
                </VChip>
              </td>
              <td class="text-center">
                {{ Math.round(check.score * (checkWeights[key as string] ?? 0) / 100) }}
              </td>
              <td class="text-body-2">
                {{ check.details }}
              </td>
            </tr>
          </tbody>
        </VTable>
      </VCardText>
    </VCard>
  </div>
</template>
