<script lang="ts" setup>
import { Badge } from '@/components/ui/badge'
import { Box } from '@/components/ui/box'
import type { Employment } from '@/modules/profile/types/employment.types'
import type { UserDetail } from '../types/user.types'

defineProps<{
  user: UserDetail
  embedded?: boolean
}>()

const EMPLOYMENT_TYPE_LABEL: Record<string, string> = {
  Permanent: 'Tetap',
  Contract: 'Kontrak',
  Internship: 'Latihan Industri',
  Freelance: 'Freelance',
}

function formatSalary(value: number | string | null | undefined): string {
  const amount = Number(value)
  if (Number.isNaN(amount)) return '-'
  return new Intl.NumberFormat('ms-MY', {
    style: 'currency',
    currency: 'MYR',
    minimumFractionDigits: 2,
  }).format(amount)
}

function formatDateLabel(value: string | null | undefined): string {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return new Intl.DateTimeFormat('ms-MY', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  }).format(date)
}

function formatEmploymentPeriod(employment: Employment): string {
  const start = formatDateLabel(employment.start_date)
  if (employment.is_current) {
    return `${start} - Kini`
  }
  const end = formatDateLabel(employment.end_date)
  return end ? `${start} - ${end}` : start
}
</script>

<template>
  <div :class="embedded ? '' : 'mt-5'">
    <Box raised="single" class="p-6">
      <div class="mb-6">
        <h3 class="text-lg font-semibold text-slate-900">Pekerjaan</h3>
        <p class="mt-1 text-sm text-slate-500">Senarai pekerjaan pengguna.</p>
      </div>

      <div v-if="user.employments?.length" class="space-y-3">
        <div
          v-for="employment in user.employments"
          :key="employment.id"
          class="rounded-lg border border-foreground/10 p-4"
        >
          <div class="flex flex-wrap items-center gap-2">
            <span class="font-medium text-slate-900">{{ employment.company_name }}</span>
            <Badge v-if="employment.is_current" class="bg-green-500 text-white">Semasa</Badge>
            <Badge look="outline">
              {{ EMPLOYMENT_TYPE_LABEL[employment.employment_type] ?? employment.employment_type }}
            </Badge>
          </div>
          <p class="mt-1 text-sm font-medium text-slate-700">{{ employment.job_title }}</p>
          <p class="mt-1 text-sm text-slate-500">{{ formatEmploymentPeriod(employment) }}</p>
          <p class="mt-1 text-sm text-slate-500">{{ formatSalary(employment.salary) }}</p>
        </div>
      </div>

      <div
        v-else
        class="rounded-lg border border-dashed border-foreground/15 p-6 text-center text-sm text-slate-500"
      >
        Tiada pekerjaan direkodkan.
      </div>
    </Box>
  </div>
</template>
