import type { InitiativeDraft } from '@/components/applicant/initiative-draft/types';
import type { DataRecord } from '@/components/applicant/lib/templateTypes';
import type { ApplicationFormState } from '@/components/applicant/initiativeFormTypes';
import {
  authorByIdMap,
  resolveDonViCongTacDisplay,
  resolveWorkUnitForContributionRow,
} from '@/components/applicant/initiative-draft/mergeContributionWorkUnits';

interface ContributionLike {
  initiativeName?: string;
  mainAuthor?: string;
  position?: string;
  representativePercent?: number;
  participants?: Array<{
    id?: number;
    fullName?: string;
    workUnit?: string;
    contributionPercent?: number;
  }>;
}

/**
 * Maps the current initiative draft (+ optional contribution blob) into flat strings
 * for common DOCX placeholders. Adjust your .docx template to use these names, or
 * edit values manually in Template Filler after upload.
 */
export function buildTemplateDataFromDraft(
  draft: InitiativeDraft,
  contribution?: Record<string, unknown> | null,
): DataRecord {
  const a = draft.application;
  const r = draft.report;
  const c = (contribution ?? {}) as ContributionLike;
  const app = a as ApplicationFormState;

  const donViResolved = resolveDonViCongTacDisplay(app, c);

  const contributionPositionResolved =
    (app.authors[0]?.workplace != null && String(app.authors[0].workplace).trim()) ||
    (c.position != null && String(c.position).trim()) ||
    app.unitName ||
    '';

  const authorsLines = a.authors
    .map((x) => `${x.name} — ${x.title} (${x.contributionPercent}%) · ${x.workplace}`)
    .join('\n');

  const trialLines =
    r.trialUnits?.map((u) => `${u.name} — ${u.address}`).join('\n') ?? '';

  const supportLines =
    a.supportStaff?.map((s) => `${s.name}: ${s.supportContent}`).join('\n') ?? '';

  const authorIds = authorByIdMap(app.authors);
  const participantsLoop =
    c.participants?.map((p) => ({
      fullName: p.fullName ?? '',
      workUnit: resolveWorkUnitForContributionRow(authorIds, p),
      contributionPercent: String(p.contributionPercent ?? ''),
    })) ?? [];

  const authorsLoop = app.authors.map((x) => ({
    name: x.name,
    title: x.title,
    workplace: x.workplace,
    contributionPercent: String(x.contributionPercent),
  }));

  const data: DataRecord = {
    initiativeName: a.initiativeName || r.initiativeName || '',
    initiativeNameReport: r.initiativeName || '',
    unitName: donViResolved,
    investorName: a.investorName,
    applicationField: a.applicationField || r.applicationField,
    firstApplyDate: a.firstApplyDate,
    contentSummary: a.contentSummary,
    confidentialInfoApp: a.confidentialInfo,
    conditionsApp: a.conditions,
    authorEvaluation: a.authorEvaluation,
    trialEvaluation: a.trialEvaluation,
    authorsList: authorsLines,
    representativeAuthor: r.representativeAuthor,
    representativePhone: r.representativePhone,
    representativeEmail: r.representativeEmail,
    introduction: r.introduction,
    currentStatus: r.currentStatus,
    purpose: r.purpose,
    solutionContent: r.solutionContent,
    implementationSteps: r.implementationSteps,
    firstAppliedUnit: r.firstAppliedUnit,
    achievedResult: r.achievedResult,
    conditionsReport: r.conditions,
    novelty: r.novelty,
    trialUnitsList: trialLines,
    supportStaffList: supportLines,
    effectivenessEconomic: r.effectiveness.economic,
    effectivenessSocial: r.effectiveness.social,
    effectivenessTeaching: r.effectiveness.teaching,
    effectivenessProductivity: r.effectiveness.productivity,
    effectivenessQuality: r.effectiveness.quality,
    effectivenessEnvironment: r.effectiveness.environment,
    effectivenessSafety: r.effectiveness.safety,
    confidentialInfoReport: r.confidentialInfo,
    submissionDate: r.submissionDate,
    authorName: r.authorName,
    contributionInitiativeName: c.initiativeName ?? '',
    contributionMainAuthor: c.mainAuthor ?? '',
    contributionPosition: contributionPositionResolved,
    contributionRepresentativePercent:
      typeof c.representativePercent === 'number' ? String(c.representativePercent) : '',
  };

  if (authorsLoop.length > 0) {
    data.authors = authorsLoop as unknown as DataRecord[];
  }
  if (participantsLoop.length > 0) {
    data.participants = participantsLoop as unknown as DataRecord[];
  }

  return data;
}
