import { type Base, genBase } from './_base'
import type { PatientFormData } from '~/schemas/patient.schema'
import type { PersonAddressFormData } from '~/schemas/person-address.schema'
import type { PersonAddressRelativeFormData } from '~/schemas/person-address-relative.schema'
import type { PersonFamiliesFormData } from '~/schemas/person-family.schema'
import type { PersonContactFormData } from '~/schemas/person-contact.schema'
import type { PersonRelativeFormData } from '~/schemas/person-relative.schema'

import { genPerson, type Person } from './person'
import type { PersonAddress } from './person-address'
import type { PersonContact } from './person-contact'
import type { PersonRelative } from './person-relative'

import { contactTypeMapping } from '~/lib/constants'

export interface PatientBase extends Base {
  person_id?: number
  newBornStatus?: boolean
  registeredAt?: Date | string | null
  status_code?: string
  number?: string
}

export interface PatientEntity extends PatientBase {
  person: Person
  personAddresses: PersonAddress[]
  personContacts: PersonContact[]
  personRelatives: PersonRelative[]
}

export interface genPatientProps {
  patient: PatientFormData
  residentAddress: PersonAddressFormData
  cardAddress: PersonAddressRelativeFormData
  familyData: PersonFamiliesFormData
  contacts: PersonContactFormData
  responsible: PersonRelativeFormData
}

export function genPatientEntity(props: genPatientProps): PatientEntity {
  const { patient, residentAddress, cardAddress, familyData, contacts, responsible } = props

  const addresses: PersonAddress[] = [{ ...genBase(), person_id: 0, ...residentAddress }]
  const familiesContact: PersonRelative[] = []
  const personContacts: PersonContact[] = []

  // jika alamat ktp sama dengan domisili saat ini
  if (cardAddress.isSameAddress) {
    addresses.push({
      ...genBase(),
      ...residentAddress,
      person_id: 0,
      locationType_code: cardAddress.locationType_code || 'identity'
    })
  } else {
    // jika alamat berbeda, tambahkan alamat relatif
    // Pastikan semua field yang diperlukan ada
    const relativeAddress = {
      ...genBase(),
      person_id: 0,
      locationType_code: cardAddress.locationType_code || 'identity',
      address: cardAddress.address || '',
      province_code: cardAddress.province_code || '',
      regency_code: cardAddress.regency_code || '',
      district_code: cardAddress.district_code || '',
      village_code: cardAddress.village_code || '',
      postalRegion_code: cardAddress.postalRegion_code || '',
      rt: cardAddress.rt,
      rw: cardAddress.rw,
    }
    addresses.push(relativeAddress)
  }

  // add data orang tua
  if (familyData.shareFamilyData === '1') {
    for (const family of familyData.families) {
      familiesContact.push({
        id: 0,
        relationship_code: family.relation,
        name: family.name,
        education_code: family.education,
        occupation_name: family.occupation,
        occupation_code: family.occupation,
        responsible: false,
      })
    }
  }

  // add kontak pasien
  if (contacts && contacts.contacts.length > 0) {
    for (const contact of contacts.contacts) {
      // Convert UI contactType to backend type_code using mapping
      const mappedContactType = contactTypeMapping[contact.contactType]

      personContacts.push({
        ...genBase(),
        person_id: 0,
        type_code: mappedContactType || '',
        value: contact.contactNumber,
      })
    }
  }

  // add penanggung jawab
  if (responsible) {
    for (const contact of responsible.contacts) {
      familiesContact.push({
        id: 0,
        relationship_code: contact.relation,
        name: contact.name,
        address: contact.address,
        phoneNumber: contact.phone,
        responsible: true,
      })
    }
  }

  return {
    person: {
      id: 0,
      name: patient.fullName,
      // alias: patient.alias,
      birthDate: patient.birthDate,
      birthRegency_code: patient.birthPlace,
      gender_code: patient.gender,
      residentIdentityNumber: patient.identityNumber,
      passportNumber: patient.passportNumber,
      drivingLicenseNumber: patient.drivingLicenseNumber,
      religion_code: patient.religion,
      education_code: patient.education,
      occupation_code: patient.job,
      occupation_name: patient.job,
      ethnic_code: patient.ethnicity,
      language_code: patient.language,
      communicationIssueStatus: patient.communicationBarrier,
      disability: patient.disabilityType || '',
      nationality: patient.nationality,
      // residentIdentityFileUrl: patient.residentIdentityFileUrl,
      // passportFileUrl: patient.passportFileUrl,
      // drivingLicenseFileUrl: patient.drivingLicenseFileUrl,
      // familyIdentityFileUrl: patient.familyIdentityFileUrl,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      deletedAt: null,
    },
    personAddresses: addresses,
    personContacts: personContacts,
    personRelatives: familiesContact,
    registeredAt: new Date(),
    status_code: 'active',
    newBornStatus: patient.isNewBorn,
    person_id: 0,
    id: 0,
    number: '',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    deletedAt: null,
  }
}

// New model
export interface Patient extends Base {
  person_id?: number
  person: Person
  newBornStatus?: boolean
  registeredAt?: Date | string | null
  status_code?: string
  number?: string
}

export function genPatient(): Patient {
  return {
    ...genBase(),
    person_id: 0,
    registeredAt: '',
    status_code: '',
    number: '',
    newBornStatus: false,
    person: genPerson(),
  }
}