export type AssetBankAccountRow = {
  bank: string
  account: string
  balance: number
  pledge: number
  seizure: string
}

export type AssetInsuranceRow = {
  company: string
  policy: string
  refund: number
  seizure: string
}

export type AssetLeaseRow = {
  address: string
  deposit: number
  monthlyRent: number
  recognizedValue: number
  seizure: string
  reason: string
}

export type AssetVehicleRow = {
  type: string
  name: string
  number: string
  year: string
  label: string
  price: number
  securedDebtAmount: number
}

export type AssetSpouseVehicleRow = {
  type: string
  name: string
  number: string
  year: string
  label: string
  price: number
  securedDebtAmount: number
}

export type AssetFacilityRow = {
  label: string
  price: number
}

export type AssetReceivableRow = {
  debtor: string
  amount: number
}

export type AssetOtherRow = {
  label: string
  price: number
}

export type AssetDocumentModel = {
  cashAmount: number
  bankAccounts: AssetBankAccountRow[]
  insurance: AssetInsuranceRow[]
  leases: AssetLeaseRow[]
  vehicles: AssetVehicleRow[]
  spouseVehicles: AssetSpouseVehicleRow[]
  realEstateNote: string
  facilities: AssetFacilityRow[]
  receivables: AssetReceivableRow[]
  retirementAmount: number
  retirementInstitution: string
  others: AssetOtherRow[]
  totalAmount: number
  exemptAmount: number
}

export const ASSET_MIN_ROWS = 7
const ASSET_BANK_DETAIL_ROW_COUNT = 6
const ASSET_RECEIVABLE_DETAIL_ROW_COUNT = 3

export const padAssetRows = <T>(rows: T[], min = ASSET_MIN_ROWS): (T | null)[] => {
  const blanks = Math.max(0, min - rows.length)
  return [...rows, ...Array(blanks).fill(null)]
}

const toNumber = (value: unknown) => {
  const normalized = String(value ?? '').replace(/[^0-9.-]/g, '')
  return Number(normalized) || 0
}

const resolveLeaseRecognizedValue = (item: any) => {
  const recognizedValue = toNumber(item?.recognizedValue)
  if (recognizedValue > 0) return recognizedValue
  return toNumber(item?.depositAmount ?? item?.deposit)
}

const formatVehicleLabel = (item: any) => {
  const legacyLabel = [item?.type || item?.name, item?.number, item?.year ? `${item.year}년식` : '']
    .filter(Boolean)
    .join(' / ')
  const currentLabel = [
    item?.type || '차량',
    toNumber(item?.price) > 0 ? `시가 ${toNumber(item.price).toLocaleString('ko-KR')}원` : '',
    toNumber(item?.securedDebtAmount) > 0 ? `피담보채무 ${toNumber(item.securedDebtAmount).toLocaleString('ko-KR')}원` : ''
  ].filter(Boolean).join(' / ')

  return currentLabel || legacyLabel
}

export const buildAssetDocumentModel = (pages: Record<string, any>) => {
  const page7 = pages['7'] || {}
  const page10 = pages['10'] || {}
  const page11 = pages['11'] || {}
  const page11_1 = pages['11_1'] || {}
  const page11_3 = pages['11_3'] || {}
  const page12 = pages['12'] || {}
  const page12_1 = pages['12_1'] || {}

  const cashAmount = toNumber(page11?.formData?.cashAmount)
  const bankAccounts: AssetBankAccountRow[] = (Array.isArray(page11?.accounts) ? page11.accounts : []).map((item: any) => ({
    bank: item.bankName || '',
    account: item.accountNumber || item.type || '',
    balance: toNumber(item.balance),
    pledge: item.hasLoan === 'Y' ? toNumber(item.pledgeAmount) || 0 : 0,
    seizure: item.isSeized === 'Y' ? '유' : '무'
  }))

  const insurance: AssetInsuranceRow[] = (Array.isArray(page11_1?.insuranceItems) ? page11_1.insuranceItems : []).map((item: any) => ({
    company: item.companyName || '',
    policy: item.policyNumber || item.productName || '',
    refund: toNumber(item.refundAmount),
    seizure: item.hasLoan === 'Y' ? '유' : '무'
  }))

  const leases: AssetLeaseRow[] = (Array.isArray(page12?.leases) ? page12.leases : []).map((item: any) => ({
    address: item.address || '',
    deposit: toNumber(item.depositAmount),
    monthlyRent: toNumber(item.monthlyRent),
    recognizedValue: resolveLeaseRecognizedValue(item),
    seizure: item.hasSeizure === 'Y' ? '유' : '무',
    reason: item.recognizedValue ? `인정가액 ${item.recognizedValue}` : ''
  }))

  const vehicles: AssetVehicleRow[] = (Array.isArray(page10?.vehicles) ? page10.vehicles : []).map((item: any) => ({
    type: String(item?.type || '자동차').trim(),
    name: String(item?.name || '').trim(),
    number: String(item?.number || '').trim(),
    year: String(item?.year || '').trim(),
    label: formatVehicleLabel(item),
    price: toNumber(item.price),
    securedDebtAmount: toNumber(item.securedDebtAmount)
  }))

  const spouseVehicles: AssetSpouseVehicleRow[] = (Array.isArray(page10?.spouseVehicles) ? page10.spouseVehicles : []).map((item: any) => ({
    type: String(item?.type || '자동차').trim(),
    name: String(item?.name || '').trim(),
    number: String(item?.number || '').trim(),
    year: String(item?.year || '').trim(),
    label: String(item.type || '').trim(),
    price: toNumber(item.price),
    securedDebtAmount: toNumber(item.securedDebtAmount)
  }))

  const realEstateNote = [
    page7.hasApplicantProperty ? `본인 명의 ${[page7.apartmentCount ? `아파트 ${page7.apartmentCount}건` : '', page7.houseCount ? `주택 ${page7.houseCount}건` : '', page7.landCount ? `토지 ${page7.landCount}건` : ''].filter(Boolean).join(', ')}` : '',
    page7.hasSpouseProperty ? `배우자 명의 ${[page7.spouseApartmentCount ? `아파트 ${page7.spouseApartmentCount}건` : '', page7.spouseHouseCount ? `주택 ${page7.spouseHouseCount}건` : '', page7.spouseLandCount ? `토지 ${page7.spouseLandCount}건` : ''].filter(Boolean).join(', ')}` : ''
  ].filter(Boolean).join(' / ')

  const facilities: AssetFacilityRow[] = (Array.isArray(page12_1?.facilities) ? page12_1.facilities : []).map((item: any) => ({
    label: [item.assetName, item.note].filter(Boolean).join(' / '),
    price: toNumber(item.estimatedValue)
  }))

  const receivables: AssetReceivableRow[] = (Array.isArray(page12?.receivables) ? page12.receivables : []).map((item: any) => ({
    debtor: [item.debtorName, item.relationship ? `(${item.relationship})` : ''].filter(Boolean).join(' '),
    amount: toNumber(item.amount)
  }))

  const retirementAmount = toNumber(page12_1?.formData?.retirementAmount)
  const retirementInstitution = page12_1?.formData?.retirementInstitution || ''

  const others: AssetOtherRow[] = (Array.isArray(page11_3?.assetItems) ? page11_3.assetItems : []).map((item: any) => ({
    label: item.description || '',
    price: toNumber(item.estimatedValue)
  }))

  const totalAmount =
    cashAmount +
    bankAccounts.reduce((sum, item) => sum + item.balance, 0) +
    insurance.reduce((sum, item) => sum + item.refund, 0) +
    leases.reduce((sum, item) => sum + item.recognizedValue, 0) +
    vehicles.reduce((sum, item) => sum + item.price, 0) +
    facilities.reduce((sum, item) => sum + item.price, 0) +
    receivables.reduce((sum, item) => sum + item.amount, 0) +
    retirementAmount +
    others.reduce((sum, item) => sum + item.price, 0)

  const exemptAmount =
    (leases[0]?.recognizedValue || 0) +
    insurance.reduce((sum, item) => sum + item.refund, 0) +
    bankAccounts.reduce((sum, item) => sum + item.balance, 0)

  const model: AssetDocumentModel = {
    cashAmount,
    bankAccounts,
    insurance,
    leases,
    vehicles,
    spouseVehicles,
    realEstateNote,
    facilities,
    receivables,
    retirementAmount,
    retirementInstitution,
    others,
    totalAmount,
    exemptAmount
  }

  return model
}

export const renderAssetTableHtml = (model: AssetDocumentModel) => {
  const money = (value: number) => `${Math.max(0, Number(value) || 0).toLocaleString('ko-KR')}&nbsp;`
  const escape = (value: string) =>
    String(value || '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
  const textOrBlank = (value: string) => {
    const normalized = String(value || '').trim()
    return normalized ? escape(normalized) : '&nbsp;'
  }
  const joinSummary = (values: string[]) => {
    const text = values.map((value) => String(value || '').trim()).filter(Boolean).join(', ')
    return text ? escape(text) : '&nbsp;'
  }

  const totalBankBalance = model.bankAccounts.reduce((sum, item) => sum + item.balance, 0)
  const totalInsuranceRefund = model.insurance.reduce((sum, item) => sum + item.refund, 0)
  const totalVehiclePrice = model.vehicles.reduce((sum, item) => sum + item.price, 0)
  const totalSpouseVehiclePrice = model.spouseVehicles.reduce((sum, item) => sum + item.price, 0)
  const spouseVehicleSummary = model.spouseVehicles
    .map((item) => {
      const parts = [
        item.label,
        item.price > 0 ? `시가 ${item.price.toLocaleString('ko-KR')}원` : '',
        item.securedDebtAmount > 0 ? `피담보채무 ${item.securedDebtAmount.toLocaleString('ko-KR')}원` : ''
      ].filter(Boolean)
      return parts.join(' / ')
    })
    .join(', ')
  const totalLeaseValue = model.leases.reduce((sum, item) => sum + item.recognizedValue, 0)
  const totalFacilityPrice = model.facilities.reduce((sum, item) => sum + item.price, 0)
  const totalReceivableAmount = model.receivables.reduce((sum, item) => sum + item.amount, 0)
  const totalOtherPrice = model.others.reduce((sum, item) => sum + item.price, 0)
  const paddedBankAccounts = padAssetRows(model.bankAccounts, ASSET_BANK_DETAIL_ROW_COUNT)
  const paddedReceivables = padAssetRows(model.receivables.slice(0, ASSET_RECEIVABLE_DETAIL_ROW_COUNT), ASSET_RECEIVABLE_DETAIL_ROW_COUNT)

  const rows: string[] = []

  rows.push(`
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131'><p align='left'><span class='fc-text-01'>&nbsp;현&nbsp;&nbsp;금</span></p></td>
      <td class='fc-border-tl' width='90'><p align='right'><span class='fc-text-01'>${money(model.cashAmount)}</span></p></td>
      <td class='fc-border-tl' width='42'><p align='center'><span class='fc-text-01'>&nbsp;</span></p></td>
      <td class='fc-border-tl' colspan='4' width='437'><p align='justify'><span class='fc-text-01'>${model.cashAmount > 0 ? '&nbsp;보유 현금' : '&nbsp;'}</span></p></td>
    </tr>
  `)

  const bankRows = paddedBankAccounts
    .map((row) => row
      ? `
        <tr bgcolor='#ffffff' style='height:29.5px;'>
          <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>${textOrBlank(row.seizure)}</span></td>
          <td class='fc-border-tl' width='125' style='padding:5px;'><span class='fc-text-01'>${textOrBlank(row.bank)}</span></td>
          <td class='fc-border-tl' width='138' style='padding:5px;'><span class='fc-text-01'>${textOrBlank(row.account)}</span></td>
          <td class='fc-border-tl' width='87' align='right'><span class='fc-text-01'>${money(row.balance)}</span></td>
          <td class='fc-border-tl' width='87' align='right'><span class='fc-text-01'>${money(row.pledge)}</span></td>
        </tr>
      `
      : `
        <tr bgcolor='#ffffff' style='height:29.5px;'>
          <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
          <td class='fc-border-tl' width='125' style='padding:5px;'><span class='fc-text-01'>&nbsp;</span></td>
          <td class='fc-border-tl' width='138' style='padding:5px;'><span class='fc-text-01'>&nbsp;</span></td>
          <td class='fc-border-tl' width='87' align='right'><span class='fc-text-01'>&nbsp;</span></td>
          <td class='fc-border-tl' width='87' align='right'><span class='fc-text-01'>&nbsp;</span></td>
        </tr>
      `)
    .join('')

  rows.push(`
    <tr bgcolor='#ffffff' style='height:43.5px;'>
      <td class='fc-border-t' rowspan='${paddedBankAccounts.length + 1}' width='131' align='left'><span class='fc-text-01'>&nbsp;예&nbsp;&nbsp;금</span></td>
      <td class='fc-border-tl' width='90' rowspan='${paddedBankAccounts.length + 1}' align='right'><span class='fc-text-01'>${money(totalBankBalance)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' width='125' align='center'><span class='fc-text-01'>&nbsp;금 융 기 관 명</span></td>
      <td class='fc-border-tl' width='138' align='center'><span class='fc-text-01'>계 좌 번 호</span></td>
      <td class='fc-border-tl' width='87' align='center'><span class='fc-text-01'>잔&nbsp;&nbsp;고</span></td>
      <td class='fc-border-tl' width='87' align='center'><span class='fc-text-01'>질권설정액</span></td>
    </tr>
    ${bankRows}
    <tr bgcolor='#ffffff' style='height:29.5px;'>
      <td class='fc-border-tl' align='center'><span class='fc-text-01'></span></td>
      <td class='fc-border-tl' colspan='4'><span class='fc-text-01'>&nbsp;예금 &nbsp; 중에서 압류할 수 없는 예금등 &nbsp; 제외</span></td>
    </tr>
  `)

  rows.push(`
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;보&nbsp;&nbsp;험</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(totalInsuranceRefund)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='5' width='437' align='left'><span class='fc-text-01'>${model.insurance.length ? `&nbsp;별지기재와 같음 (${model.insurance.length}건)<br>&nbsp;(예상환급금 &nbsp; 중에서 압류할 수 없는 보험금 &nbsp; 제외)` : '&nbsp;'}</span></td>
    </tr>
  `)

  rows.push(`
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;자동차/선박/오토바이</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(totalVehiclePrice)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='5' width='437' align='left'><span class='fc-text-01'>${model.vehicles.length ? `&nbsp;별지기재와 같음 (${model.vehicles.length}건)` : '&nbsp;'}</span></td>
    </tr>
  `)

  if (model.spouseVehicles.length) {
    rows.push(`
      <tr bgcolor='#ffffff' height='34'>
        <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;배우자 명의 차량</span></td>
        <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(totalSpouseVehiclePrice)}</span></td>
        <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
        <td class='fc-border-tl' colspan='5' width='437' align='left'><span class='fc-text-01'>${spouseVehicleSummary ? escape(spouseVehicleSummary) : '&nbsp;'}</span></td>
      </tr>
    `)
  }

  rows.push(`
    <tr bgcolor='#ffffff'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;임차보증금</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(totalLeaseValue)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' style='height:51.5px;' align='left'><span class='fc-text-01'>${model.leases.length ? `&nbsp;별지기재와 같음 (${model.leases.length}건)` : '&nbsp;'}</span></td>
    </tr>
  `)

  rows.push(`
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;부&nbsp; 동&nbsp; 산</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(0)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='312' align='left'><span class='fc-text-01'>${textOrBlank(model.realEstateNote)}</span></td>
    </tr>
  `)

  rows.push(`
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;사업용 설비, 비품 등</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(totalFacilityPrice)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='312' align='left'><span class='fc-text-01'>${joinSummary(model.facilities.map((item) => `${item.label}${item.price ? ` / 예상가액 ${item.price.toLocaleString('ko-KR')}` : ''}`))}</span></td>
    </tr>
  `)

  rows.push(paddedReceivables.map((item, index) => `
    <tr bgcolor='#ffffff' style='height:43.5px;'>
      ${index === 0 ? `<td class='fc-border-t' rowspan='${paddedReceivables.length}' width='131' align='left'><span class='fc-text-01'>&nbsp;대여금 채권</span></td>
      <td class='fc-border-tl' rowspan='${paddedReceivables.length}' width='90' align='right'><span class='fc-text-01'>${money(totalReceivableAmount)}</span></td>` : ''}
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='5' width='437' align='left'><table cellpadding='0' cellspacing='0' width='100%'><tr><td width='50%'><span class='fc-text-01'>&nbsp;상대방 채무자 ${index + 1} : ${item ? textOrBlank(item.debtor) : '&nbsp;'}</span></td><td width='50%'><span class='fc-text-01'>채권액 : ${item ? money(item.amount) : '&nbsp;'}</span></td></tr></table></td>
    </tr>
  `).join(''))

  rows.push(`
    <tr bgcolor='#ffffff' height='54'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;예상퇴직금</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(model.retirementAmount)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='437' align='left' style='padding:5px;'><span class='fc-text-01'>${model.retirementInstitution ? `근무처 : ${escape(model.retirementInstitution)}` : '&nbsp;'}</span></td>
    </tr>
  `)

  rows.push(`
    <tr bgcolor='#ffffff' height='54'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;기타 (&nbsp;&nbsp;)</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(totalOtherPrice)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='437' align='left' style='padding:5px;'><span class='fc-text-01'>${joinSummary(model.others.map((item) => `${item.label}${item.price ? ` / 예상가액 ${item.price.toLocaleString('ko-KR')}` : ''}`))}</span></td>
    </tr>
  `)

  rows.push(`
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;합&nbsp;&nbsp;계</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(model.totalAmount)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='437' align='left'><span class='fc-text-01'>&nbsp;</span></td>
    </tr>
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;면제재산 신청금액</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(model.exemptAmount)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='437' align='left'><span class='fc-text-01'>&nbsp;${model.exemptAmount > 0 ? '면제재산 신청 예정' : '해당사항 없음'}</span></td>
    </tr>
    <tr bgcolor='#ffffff' height='34'>
      <td class='fc-border-t' width='131' align='left'><span class='fc-text-01'>&nbsp;청산가치</span></td>
      <td class='fc-border-tl' width='90' align='right'><span class='fc-text-01'>${money(model.totalAmount)}</span></td>
      <td class='fc-border-tl' width='42' align='center'><span class='fc-text-01'>&nbsp;</span></td>
      <td class='fc-border-tl' colspan='4' width='437' align='left'><span class='fc-text-01'>&nbsp;</span></td>
    </tr>
  `)

  return `
    <table style='border-collapse:collapse' border='1' bordercolor='#000000' cellpadding='0' cellspacing='0' width='100%' align='center' class='docxline'>
      <tr bgcolor='#ffffff' height='34'>
        <td class='fc-border-o' width='131' align='center'><span class='fc-text-01'>명&nbsp;&nbsp;칭</span></td>
        <td class='fc-border-l' width='90' align='center'><span class='fc-text-01'>금액 (시가)<br></span></td>
        <td class='fc-border-l' width='42' align='center'><span class='fc-text-01'>압류등<br>유ㆍ무</span></td>
        <td class='fc-border-l' width='437' colspan='4' align='center'><span class='fc-text-01'>비&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;고</span></td>
      </tr>
      ${rows.join('')}
    </table>
  `
}
