import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { toast } from '~/components/pub/ui/toast'
import { getList as getSepList } from '~/services/vclaim-sep.service'
import { getList as getMemberList } from '~/services/vclaim-member.service'

export function useIntegrationSepDetail() {
  const route = useRoute()
  const isLoading = ref(false)
  const sepData = ref<any>(null)
  const valueObjects = ref<any>({})

  const noSep = computed(() => {
    return typeof route.params.id === 'string' ? route.params.id : ''
  })

  async function getSepDetail() {
    if (!noSep.value) {
      toast({
        title: 'Gagal',
        description: 'No SEP tidak ditemukan di URL',
        variant: 'destructive',
      })
      return
    }

    try {
      isLoading.value = true
      const result = await getSepList({ number: noSep.value })

      if (result.success && result.body?.response) {
        const response = result.body.response
        sepData.value = response
        valueObjects.value = {
          sepNumber: response.noSep || noSep.value,
          eSep: response.eSEP === 'True' ? 'yes' : 'no',
          serviceType:
            response.jnsPelayanan === 'Rawat Jalan' ? '2' : response.jnsPelayanan === 'Rawat Inap' ? '1' : null,
          sepDate: response.tglSep ? new Date(response.tglSep).toISOString().split('T')[0] : '',
          cardNumber: response.peserta?.noKartu || '-',
          patientName: response.peserta?.nama || '-',
          phoneNumber: response.peserta?.noTelp || '-',
          medicalRecordNumber: response.peserta?.noMr || '-',
          memberInsurance: response.peserta?.asuransi || '-',
          memberClass: response.peserta?.hakKelas || '-',
          memberGender: response.peserta?.kelamin || '-',
          memberBirthDate: response.peserta?.tglLahir || '-',
          memberType: response.peserta?.jnsPeserta || '-',
          referralLetterNumber: response.noRujukan || '-',
          diagnosisName: response.diagnosa || '-',
          attendingDoctor: response.dpjp?.kdDPJP || '-',
          attendingDoctorName: response.dpjp?.nmDPJP || '-',
          polyName: response.poli || '-',
          cob: response.cob === '1' ? 'yes' : 'no',
          cataract: response.katarak === '1' ? 'yes' : 'no',
          clinicExcecutive: response.poliEksekutif === '1' ? 'yes' : 'no',
          procedureType: response.flagProcedure?.kode || '-',
          procedureTypeName: response.flagProcedure?.nama || '-',
          supportCode: response.kdPenunjang?.kode || '-',
          supportCodeName: response.kdPenunjang?.nama || '-',
          note: response.catatan || response.informasi || '-',
          classLevel: response.kelasRawat || '-',
          classLevelUpgrade: response.klsRawat?.klsRawatNaik || '-',
          classPaySource: response.klsRawat?.pembiayaan || '-',
          responsiblePerson: response.klsRawat?.penanggungJawab || response.penjamin || '-',
          purposeOfVisit: response.tujuanKunj?.kode || '-',
          purposeOfVisitName: response.tujuanKunj?.nama || '-',
          serviceAssessment: response.assestmenPel?.kode || '-',
          serviceAssessmentName: response.assestmenPel?.nama || '-',
          trafficAccident: response.kdStatusKecelakaan || '',
          trafficAccidentName: response.nmstatusKecelakaan || '',
          lpNumber: response.kontrol?.noSurat || '-',
          accidentDate: response.lokasiKejadian?.tglKejadian || '-',
          accidentNote: response.lokasiKejadian?.ketKejadian || '-',
          accidentProvince: response.lokasiKejadian?.kdProp || '-',
          accidentCity: response.lokasiKejadian?.kdKab || '-',
          accidentDistrict: response.lokasiKejadian?.kdKec || '-',
          accidentLocation: response.lokasiKejadian?.lokasi || '-',
          suplesi: response.jnsPelayanan === 'Rawat Jalan' ? 'yes' : 'no',
          suplesiNumber: response.jnsPelayanan === 'Rawat Jalan' ? response.noRujukan || '-' : '-',
          controlLetterNumber: response.kontrol?.noSurat || '-',
          controlLetterDoctor: response.kontrol?.kdDokter || '-',
          controlLetterDoctorName: response.kontrol?.nmDokter || '-',
        }
        if (valueObjects.value?.cardNumber !== '-') {
          const resultMember = await getMemberList({
            mode: 'by-card',
            number: valueObjects.value.cardNumber,
            date: new Date().toISOString().substring(0, 10),
          })
          if (resultMember && resultMember.success && resultMember.body) {
            const memberRaws = resultMember.body?.response || null
            valueObjects.value['nationalIdentity'] = memberRaws?.peserta?.nik || ''
            valueObjects.value['phoneNumber'] = memberRaws?.peserta?.mr?.noTelepon || ''
            valueObjects.value['classLevel'] = memberRaws?.peserta?.hakKelas?.kode || ''
            valueObjects.value['status'] = memberRaws?.statusPeserta?.kode || ''
          }
        }
      } else {
        toast({
          title: 'Gagal',
          description: 'Data SEP tidak ditemukan',
          variant: 'destructive',
        })
        await navigateTo('/integration/bpjs-vclaim/sep')
      }
    } catch (error: any) {
      console.error('Error loading SEP detail:', error)
      toast({
        title: 'Gagal',
        description: error?.message || 'Gagal memuat data SEP',
        variant: 'destructive',
      })
      await navigateTo('/integration/bpjs-vclaim/sep')
    } finally {
      isLoading.value = false
    }
  }

  return {
    isLoading,
    noSep,
    sepData,
    valueObjects,
    getSepDetail,
  }
}
