/**
 * Pure form logic for the Βεβαίωση Οφειλής form: types, parsing, validation and
 * mapping between the API model and the form state. No React here, so it can be
 * unit-tested directly.
 */
import {
    Codebtor, KaeRow, Vevaiosi, VevaiosiAttachment, VevaiosiFile, VevaiosiPayload, primaryDebtor
} from "../../../../models/Ked/Vevaiosi";

/* ------------------------------- config -------------------------------- */

// ΚΕΔ rule I assumed: the KAE amounts must add up to the total. Set false to disable.
export const REQUIRE_KAE_SUM_MATCH = true;
// Spec: .pdf, .zip, .xlsx, .docx, .jpg, .eml, max 15MB. FilesSection derives its hint/error text from these.
export const MAX_FILE_SIZE = 15 * 1024 * 1024;
export const ALLOWED_EXT = ['pdf', 'zip', 'xls', 'xlsx', 'docx', 'jpg', 'jpeg', 'eml'];

const AFM_RE = /^\d{9}$/;
const REQUIRED = 'Υποχρεωτικό πεδίο.';
const AFM_MSG = 'Το ΑΦΜ πρέπει να έχει 9 ψηφία.';

/* -------------------------------- types -------------------------------- */

// All text inputs are kept as strings while editing; they are parsed only in toPayload.
// signatory_id is the signer's AFM (string, from GET /lookups); '' while nothing is selected.
export type FormState = {
    afm: string; debtor_name: string; phone: string; codebtors: Codebtor[];
    total_amount: string; financial_year: string; decision_number: string; comments: string;
    kae_rows: KaeRow[]; files: VevaiosiFile[]; signatory_id: number | string;
};

// Flat map of field key -> message. Row fields use errKey() so keys stay consistent.
export type Errors = Record<string, string>;

export type SetField = <K extends keyof FormState>(key: K, value: FormState[K]) => void;

// A file picked locally that hasn't reached the backend yet (only exists before the first save).
export type NewVevaiosiFile = { title: string; file: File };

// Result of a save: when the save created the record together with its files, the parent
// returns the server copies of those files (with uuid) so the form can replace its local ones.
export type SaveResult = { ok: boolean; files?: VevaiosiAttachment[] };

export const errKey = {
    codebtor: (id: string, field: string) => `cd_${id}_${field}`,
    kae: (id: string, field: string) => `kae_${id}_${field}`,
};

/* ------------------------------- helpers ------------------------------- */

// Client-side row id, only used for React keys and error keys (never sent to the API).
export const uid = () => Math.random().toString(36).slice(2, 10);
export const emptyKae = (): KaeRow => ({id: uid(), kae: '', amount: ''});
export const emptyCodebtor = (): Codebtor => ({id: uid(), afm: '', name: '', relation: ''});

export const money = new Intl.NumberFormat('el-GR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
// accepts the backend's decimal string ('600.00') as well as numbers; shown with a dot and 2 decimals ('600.00').
// parseAmount reads it back unchanged: without a comma, the dot is the decimal separator.
const toInputAmount = (v?: number | string | null) => {
    if (v == null || v === '') return '';
    const n = Number(v);
    return Number.isNaN(n) ? '' : n.toFixed(2);
};

export const digitsOnly = (v: string) => v.replace(/\D/g, '');
// tolerates a missing name: the backend's attachments carry only title + filepath
export const extOf = (name?: string | null) => (name ?? '').split('.').pop()?.toLowerCase() ?? '';
// "minio://beveoseis/10-2026.pdf" -> "10-2026.pdf"
const fileNameOf = (path?: string) => path?.split('/').pop() || undefined;

// Accepts "1250", "1250,5", "1.250,50"; returns NaN when invalid.
// Note: without a comma, "1.25" is read as 1.25 (decimal), not 125.
export const parseAmount = (s: string): number => {
    const t = s.trim().replace(/\s/g, '');
    if (!t) return NaN;
    const normalized = t.includes(',') ? t.replace(/\./g, '').replace(',', '.') : t;
    return /^\d+(\.\d{1,2})?$/.test(normalized) ? Number(normalized) : NaN;
};

// Display-only running total; invalid amounts count as 0.
export const sumKae = (rows: KaeRow[]) =>
    rows.reduce((s, r) => {
        const a = parseAmount(r.amount);
        return s + (Number.isNaN(a) ? 0 : a);
    }, 0);

/* ------------------------- decision in comments ------------------------ */

// What follows the decision in the comments: "11/2026 - ...".
// ΚΕΔ rejects comments that hold nothing but the decision number, so the separator is always added.
export const DECISION_SEP = ' - ';

// Escapes regex metacharacters so a value like "11/2026" or "12.3/2026" is matched literally.
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

// The token must start the text or follow whitespace, and end the text or precede whitespace.
const tokenRe = (token: string, flags = '') =>
    new RegExp(`(^|\\s)${escapeRe(token)}(?=\\s|$)`, flags);

// true for "11/2026", "Απόφαση 11/2026", "11/2026 σχετικά"; false for "test11/2026" or "11/2026x".
export const hasStandaloneToken = (text: string, token: string) => tokenRe(token).test(text);

/**
 * Keeps the decision number/year at the start of the comments, as "11/2026 - ", while the user edits the decision field.
 * - Replaces the first standalone occurrence of the previous value with the new one;
 *   the " - " and the user's text after it stay as they are (and " - " is added if a leading prefix lacks it).
 * - Removes it, together with its " - ", when the decision is cleared.
 * - Otherwise puts "new - " in front of whatever is there (empty comments -> just "new - ").
 * First occurrence, not last: the prefix is at the start, so a matching number the user typed
 * later in their own text is never the one replaced.
 */
export const syncDecisionInComments = (comments: string, prev: string, next: string): string => {
    const p = prev.trim();
    const n = next.trim();

    if (p) {
        const m = tokenRe(p).exec(comments);
        if (m) {
            const start = m.index + m[1].length; // skip the leading whitespace, if any
            const end = start + p.length;
            if (n) {
                const rest = comments.slice(end);
                // the prefix at the start always keeps its " - ": older records saved as plain "12/2026"
                // (or "12/2026 abc") get it added on the first edit
                if (start === 0 && !/^\s*-/.test(rest)) return `${n}${DECISION_SEP}${rest.replace(/^\s+/, '')}`;
                return comments.slice(0, start) + n + rest;
            }

            // decision cleared: drop the token together with its " - " (or its leading space)
            const before = comments.slice(0, m.index);
            let after = comments.slice(end).replace(/^\s*-(\s|$)/, '');
            if (!before) after = after.replace(/^\s+/, '');
            return before + after;
        }
    }

    if (!n) return comments;
    if (hasStandaloneToken(comments, n)) return comments;
    // the trailing space of " - " goes away on save (toPayload trims), leaving "11/2026 -"
    return `${n}${DECISION_SEP}${comments.replace(/^\s+/, '')}`;
};

/* ------------------------------- mapping ------------------------------- */

// Server files -> form files. The client `id` is only a React key; the backend identifies files by `uuid`.
// The record returns only {title, filepath}, so the name comes from the path (then the title) and the size is 0.
// Without a uuid such a file can't be deleted through the file routes; removeFile in View says so.
export const toFormFiles = (files: VevaiosiAttachment[]): VevaiosiFile[] =>
    files.map(f => ({
        id: uid(),
        uuid: f.uuid,
        title: f.title,
        name: f.name ?? fileNameOf(f.filepath) ?? f.title,
        size: f.size ?? 0,
    }));

// Files that exist only in the browser (picked before the record had an id).
// Server files have a uuid and no File object, so they are never included here.
export const newFilesOf = (f: FormState): NewVevaiosiFile[] =>
    f.files.filter(x => !x.uuid && x.file).map(x => ({title: x.title, file: x.file!}));

// numeric lookup code from the backend ("1", "82838") -> select value; '' when missing
const toCode = (v?: string | null): number | '' => (v == null || v === '' ? '' : Number(v));

// Single record (GET /certifiedDebts/status) -> form state.
// The debtor and co-debtors both come from `debtors`: the primary one fills section Α, the rest are co-debtors.
export const toFormState = (d?: Vevaiosi): FormState => {
    const primary = d ? primaryDebtor(d) : undefined;
    return {
        afm: d?.afm ?? '',
        debtor_name: primary?.fullName ?? '',
        phone: primary?.phone ?? '',
        codebtors: (d?.debtors ?? [])
            .filter(x => x !== primary)
            .map(c => ({id: uid(), afm: c.afm, name: c.fullName ?? '', relation: toCode(c.relationCode)})),
        total_amount: toInputAmount(d?.sunolo),
        financial_year: d?.fiscalYear ?? '',
        decision_number: d?.apofNoEtos ?? '',
        comments: d?.comments ?? '',
        // a new form always starts with one empty KAE row
        kae_rows: d?.kaeLines?.length
            ? d.kaeLines.map(r => ({id: uid(), kae: toCode(r.kae), amount: toInputAmount(r.amount)}))
            : [emptyKae()],
        files: toFormFiles(d?.attachments ?? []),
        signatory_id: d?.afmYpogr ?? '',
    };
};

/**
 * Form state -> backend `params` (backend key names where one exists).
 * Files are not included: they go separately (newFilesOf / upload endpoint).
 */
export const toPayload = (f: FormState): VevaiosiPayload => ({
    afm: f.afm.trim(),
    debtorName: f.debtor_name.trim(),
    phone: f.phone.trim(),
    synypochreoi: f.codebtors.map(c => ({afm: c.afm.trim(), fullName: c.name.trim(), relation: Number(c.relation)})),
    sunolo: parseAmount(f.total_amount),
    fiscalYear: Number(f.financial_year),
    apofNoEtos: f.decision_number.trim(),
    comments: f.comments.trim(),
    kaeLines: f.kae_rows.map(r => ({kae: Number(r.kae), amount: parseAmount(r.amount)})),
    // the signer's AFM as a string: Number() would drop leading zeros ("012345678" -> 12345678)
    afmYpogr: String(f.signatory_id),
});

/* ------------------------------ validation ----------------------------- */

/**
 * True when every required field has a value (presence only, not format).
 * Drives the disabled state of ΑΠΟΘΗΚΕΥΣΗ / ΑΠΟΣΤΟΛΗ on a new record. Format rules
 * (9-digit ΑΦΜ, valid amounts, ΚΑΕ sum, decision in comments) stay in validate(),
 * so the user still gets a message for them when clicking.
 * Same required set as validate(): phone is the only optional field; every co-debtor row
 * that was added must be complete.
 */
export const requiredFilled = (f: FormState): boolean => {
    const has = (s: string) => s.trim() !== '';
    return has(f.afm)
        && has(f.debtor_name)
        && f.codebtors.every(c => has(c.afm) && has(c.name) && c.relation !== '')
        && has(f.total_amount)
        && has(f.financial_year)
        && has(f.decision_number)
        && has(f.comments)
        && f.kae_rows.length > 0
        && f.kae_rows.every(r => r.kae !== '' && has(r.amount))
        && f.signatory_id !== '';
};

export const validate = (f: FormState): Errors => {
    const e: Errors = {};
    const currentYear = new Date().getFullYear();

    // Α. debtor
    if (!AFM_RE.test(f.afm.trim())) e.afm = AFM_MSG;
    if (!f.debtor_name.trim()) e.debtor_name = REQUIRED;

    f.codebtors.forEach(c => {
        if (!AFM_RE.test(c.afm.trim())) e[errKey.codebtor(c.id, 'afm')] = AFM_MSG;
        if (!c.name.trim()) e[errKey.codebtor(c.id, 'name')] = REQUIRED;
        if (c.relation === '') e[errKey.codebtor(c.id, 'relation')] = REQUIRED;
    });

    // Β. debt
    const total = parseAmount(f.total_amount);
    // the amount inputs only accept digits and "." now, so the example uses a dot
    if (!(total > 0)) e.total_amount = 'Συμπληρώστε έγκυρο ποσό (π.χ. 1250.50).';

    const year = Number(f.financial_year);
    if (!/^\d{4}$/.test(f.financial_year.trim()) || year < 2000 || year > currentYear + 1) {
        e.financial_year = `Συμπληρώστε έγκυρο έτος (π.χ. ${currentYear}).`;
    }

    const decision = f.decision_number.trim();
    if (!decision) e.decision_number = REQUIRED;

    // comments must contain the decision number/year as a separate word
    if (!f.comments.trim()) e.comments = REQUIRED;
    else if (decision && !hasStandaloneToken(f.comments, decision)) {
        e.comments = `Τα σχόλια πρέπει να περιέχουν τον αριθμό απόφασης/έτος ("${decision}") χωρισμένο με κενό από το υπόλοιπο κείμενο.`;
    }

    // KAE rows; the sum check only runs when every row amount is valid
    let kaeSum = 0;
    let kaeValid = true;
    f.kae_rows.forEach(r => {
        if (r.kae === '') e[errKey.kae(r.id, 'kae')] = REQUIRED;
        const a = parseAmount(r.amount);
        if (!(a > 0)) { e[errKey.kae(r.id, 'amount')] = 'Έγκυρο ποσό.'; kaeValid = false; }
        else kaeSum += a;
    });
    // compare in cents to avoid floating point noise
    if (REQUIRE_KAE_SUM_MATCH && kaeValid && total > 0 && Math.round(kaeSum * 100) !== Math.round(total * 100)) {
        e.kae_sum = `Το άθροισμα των ΚΑΕ (${money.format(kaeSum)}€) πρέπει να ισούται με το συνολικό ποσό (${money.format(total)}€).`;
    }

    // Ε. signatory
    if (f.signatory_id === '') e.signatory_id = REQUIRED;

    return e;
};
