import {FilterStatusType} from "../ReactComponents";

// value is a string for signers (AFM keeps its leading zeros), a number for the rest
export type LookupOption = { value: number | string; name: string };

export interface VevaiosiLookups {
    kae: LookupOption[];
    relations: LookupOption[];
    signatories: LookupOption[];
}

// a stored file as the file requests reference it; `uuid` identifies it
export interface StoredVevaiosiFile { uuid: string; title: string; name: string; size: number }

// An attachment as GET /certifiedDebts/status returns it. Confirmed so far: {title, filepath}
// (e.g. "minio://beveoseis/10-2026.pdf"), with no uuid / name / size.
// Those stay optional so the form works with either shape.
export interface VevaiosiAttachment {
    title: string;
    filepath?: string;
    uuid?: string;
    name?: string;
    size?: number;
}

/* ------------------------- file requests (saved record) ------------------------- */
// Once the record has an id, every add / delete is one request whose body has two parts:
// `existing` (the stored files) and, separately, the file being added or deleted.

// the file being added: no uuid yet (the backend assigns it), plus the binary
export interface NewVevaiosiFileUpload { title: string; name: string; size: number; file: File }

// add: all stored files + the new one
export interface VevaiosiFileUploadBody {
    existing: StoredVevaiosiFile[];
    new: NewVevaiosiFileUpload;
}

// delete: all stored files (including the one being removed) + the one being removed
export interface VevaiosiFileDeleteBody {
    existing: StoredVevaiosiFile[];
    delete: StoredVevaiosiFile;
}

export type VevaiosiFileSyncBody = VevaiosiFileUploadBody | VevaiosiFileDeleteBody;

// form-only types (ids are client-side, for React keys)
export interface Codebtor { id: string; afm: string; name: string; relation: number | '' }
export interface KaeRow { id: string; kae: number | ''; amount: string }
// a file in the form: either a server file (has uuid) or a local one picked
// before the first save (has the File object, no uuid yet)
export interface VevaiosiFile { id: string; uuid?: string; title: string; name: string; size: number; file?: File }

// The save request body (sent flat, no command / params wrapper).
// Keys use the backend names where one exists (debtorName / phone / synypochreoi are request-only names;
// the record returns them inside `debtors`). The API layer sends `phone` as `debtorPhone`.
// Files are not part of it: on create they go alongside it as multipart (see saveVevaiosi),
// after that every add / delete is a separate request (see VevaiosiFileSyncBody / syncVevaiosiFiles).
export interface VevaiosiPayload {
    afm: string;
    debtorName: string;
    phone: string;
    synypochreoi: { afm: string; fullName: string; relation: number }[];
    sunolo: number;                 // total amount
    fiscalYear: number;
    apofNoEtos: string;             // decision number / year
    comments: string;
    kaeLines: { kae: number; amount: number }[];
    afmYpogr: string;               // the signer's AFM (from GET /lookups signers); stored as afmYpogr
}

// What actually goes to the backend: the form data plus the action flag.
// submit: false -> save as draft, true -> save and send to ΚΕΔ in the same request.
// Added by the API layer (saveVevaiosi), so the form keeps producing plain VevaiosiPayload.
export interface VevaiosiSaveParams extends VevaiosiPayload {
    submit: boolean;
}

/* -------------------------------- status -------------------------------- */
// The backend sends a status CODE (string) plus a ready-made label (statusLabel).
// All codes confirmed by GET /statuses.
export const VEVAIOSI_STATUS = {
    DRAFT: 'draft',                                         // Πρόχειρο
    SENT: 'sent',                                           // Απεστάλη
    CERTIFIED_PENDING_CLOSEDAY: 'certified_pending_closeday', // Βεβαιώθηκε — αναμονή ΑΤΒ
    CERTIFIED: 'certified',                                 // Βεβαιωμένη
    REJECTED: 'failed',                                     // Απορρίφθηκε
    NEEDS_RECONCILIATION: 'needs_reconciliation',           // Εκκρεμεί έλεγχος
} as const;

export const DRAFT_STATUS: string = VEVAIOSI_STATUS.DRAFT;

// UI colour per status code; unknown codes fall back to the list's default styling
const UI_TYPE_BY_STATUS: Record<string, FilterStatusType> = {
    [VEVAIOSI_STATUS.DRAFT]: 'pending',
    [VEVAIOSI_STATUS.SENT]: 'success',
    [VEVAIOSI_STATUS.CERTIFIED_PENDING_CLOSEDAY]: 'pending',  // certified, still waiting for the ΑΤΒ
    [VEVAIOSI_STATUS.CERTIFIED]: 'success',
    [VEVAIOSI_STATUS.REJECTED]: 'error',
    [VEVAIOSI_STATUS.NEEDS_RECONCILIATION]: 'pending',        // needs a manual check
};

export const statusUiType = (status?: string | null): FilterStatusType | undefined =>
    status ? UI_TYPE_BY_STATUS[status] : undefined;

/* -------------------------------- record -------------------------------- */

// one identity the debt is certified against (debtor, and presumably each co-debtor), with its payment code
export interface Taftotita {
    afm: string;
    fullName: string | null;
    payId: string | null;
}

// One person on the record, as GET /certifiedDebts/status returns it.
// The debtor is isPrimary: true (position 0); every co-debtor follows with its relation.
export interface VevaiosiDebtor {
    afm: string;
    position: number;
    isPrimary: boolean;
    fullName: string | null;
    phone: string | null;
    relationCode: string | null;        // relation code from GET /lookups, e.g. "1"; null for the debtor
    relationCategory: string | null;    // e.g. "2"; null for the debtor
    amount: string | null;
    origAmount: string | null;
    lineNo: string | number | null;
    taftotitaOfeilis: string | null;
}

export interface VevaiosiInstallment { aa: string; dueDate: string; amount: string }

/* ---------------------------- payment progress ---------------------------- */
// POST /certifiedDebts/paymentProgress (ΕΛΕΓΧΟΣ ΠΛΗΡΩΜΩΝ sidebar), already normalized by the API layer
// (toPaymentProgress in ked.ts), so the screen never depends on the backend's key names.
// Amounts are decimal strings ("600.35"); null = not known.
export interface VevaiosiPaymentProgress {
    debtId: string | null;              // Ταυτότητα Οφειλής, e.g. "099062654910104214686195400002"
    originalAmount: string | null;      // ΑΡΧΙΚΟ ΒΕΒΑΙΩΘΕΝ
    reducedAmount: string | null;       // ΜΕΙΩΣΗ
    paidAmount: string | null;          // ΠΛΗΡΩΘΕΝ
    balance: string | null;             // ΥΠΟΛΟΙΠΟ
    writtenOffAmount: string | null;    // ΔΙΑΓΡΑΦΕΝ
    overdueAmount: string | null;       // ΛΗΞΙΠΡΟΘΕΣΜΟ
    // Τελευταία ενημέρωση: when ΚΕΔ last updated this debt, with its reference number
    kedUpdatedAt: string | null;        // ISO date-time
    kedRef: string | null;              // e.g. "10089881315"
}

// A record as the list endpoint returns it; the optional fields only come from the single-record endpoint.
export interface Vevaiosi {
    id: number;
    status: string;                     // code, e.g. 'certified'
    statusLabel: string;                // e.g. 'Βεβαιωμένη'
    locked: boolean;
    auditProtocol: string | null;       // e.g. '14/08-10-2026'

    afm: string;
    debtorName?: string | null;         // debtor name as the list response returns it
    apofNoEtos: string | null;          // decision number / year
    fiscalYear: string | null;          // string on the wire, e.g. '2026'
    kae: string | null;                 // single KAE code on the list record
    sunolo: string | null;              // decimal as string, e.g. '600.00'

    doy: string | null;
    mcNo: string | null;                // χρηματικός κατάλογος number
    mcDate: string | null;
    atbNo: string | null;
    atbDate: string | null;

    createdAt: string;                  // ISO with offset
    submittedAt: string | null;
    certifiedAt: string | null;

    errorCode: string | number | null;
    errorDescr: string | null;

    taftotites: Taftotita[];

    // single record only (GET /certifiedDebts/status); not in the list response
    comments?: string | null;
    debtors?: VevaiosiDebtor[];
    kaeLines?: { kae: string; amount: string }[];   // amounts as decimal strings, e.g. "401.00"
    afmYpogr?: string | null;                        // signer AFM
    nameYpogr?: string | null;                       // signer name, e.g. "ΕΠΩΝΥΜΟ ΟΝΟΜΑ"
    attachments?: VevaiosiAttachment[];              // confirmed: {title, filepath}
    pending?: boolean;                               // true while ΚΕΔ hasn't answered; the UI polls meanwhile
    insFrequency?: string | null;
    lastDayRule?: string | null;
    installments?: VevaiosiInstallment[];
    discountDate?: string | null;
    discountPcg?: string | null;
}

export interface GetVevaioseisParams {
    status: string;                     // status code ('draft', 'certified', ...) or '' for all
    page: number;
    page_size: number;
    search?: string;
    date_from?: string | null;
    date_to?: string | null;
    order_by?: 'created_at' | string;
    order?: 'asc' | 'desc';
}

// The primary debtor of a single record (falls back to the first one).
export const primaryDebtor = (v: Pick<Vevaiosi, 'debtors'>) =>
    v.debtors?.find(d => d.isPrimary) ?? v.debtors?.[0];

// Debtor name: from `debtors` when present (single record), else from the identities (list record).
export const debtorName = (v: Pick<Vevaiosi, 'afm' | 'taftotites' | 'debtors' | 'debtorName'>) =>
    primaryDebtor(v)?.fullName
    ?? v.debtorName
    ?? v.taftotites?.[0]?.fullName
    ?? null;

// strict on purpose: unknown status or a locked record is NOT treated as a draft
export const isDraft = (v: Pick<Vevaiosi, 'status' | 'locked'>) =>
    v.status === DRAFT_STATUS && !v.locked;

export const isRejected = (v: Pick<Vevaiosi, 'status'>) => v.status === VEVAIOSI_STATUS.REJECTED;

// ΠΡΟΧΕΙΡΟ and ΑΠΟΡΡΙΦΘΗΚΕ can be edited and deleted; everything else is view-only.
// Rejected is not checked against `locked`: the backend may send it locked.
export const canEdit = (v: Pick<Vevaiosi, 'status' | 'locked'>) => isDraft(v) || isRejected(v);
export const canDelete = canEdit;

// Only a certified debt has a collection to follow (Παρακολούθηση Είσπραξης).
// GUESS: certified_pending_closeday is left out because it has no ΑΤΒ yet; add it here if ΚΕΔ already tracks it.
export const hasPaymentProgress = (v: Pick<Vevaiosi, 'status'>) => v.status === VEVAIOSI_STATUS.CERTIFIED;
