import React, {useMemo} from 'react';
import CustomFormSection from "../../../../components/UI/Forms/CustomFormSection/CustomFormSection";
import {KaeRow, LookupOption} from "../../../../models/Ked/Vevaiosi";
import {DeleteRowButton, SelectField, TextField} from "./fields";
import {digitsOnly, errKey, Errors, FormState, money, SetField, sumKae} from "./vevaiosiForm";

interface Props {
    form: FormState
    errors: Errors
    disabled: boolean
    kaeOptions: LookupOption[]
    setField: SetField
    onAddKae: () => void
    onRemoveKae: (id: string) => void
    onUpdateKae: (id: string, patch: Partial<KaeRow>) => void
    // focus left the total amount: View copies it to the ΚΑΕ row when there is only one
    onTotalBlur: () => void
}

// Amounts: digits and a single "." only, at most 2 decimals.
// A comma becomes "." first, so the Greek numpad decimal key (and pasted "625,38") still works.
const amountChars = (v: string) => {
    const cleaned = v.replace(/,/g, '.').replace(/[^\d.]/g, '');
    const dot = cleaned.indexOf('.');
    if (dot === -1) return cleaned;
    // keep the first dot, drop any later ones, cap the decimals at 2
    return cleaned.slice(0, dot + 1) + cleaned.slice(dot + 1).replace(/\./g, '').slice(0, 2);
};

const AMOUNT_PLACEHOLDER = 'Εισάγετε το πλήρες ποσό, π.χ. 625.38';

const DECISION_PREFIX = 'ΑΡ. ΑΠΟΦΑΣΗΣ / ΕΤΟΣ: ';

// First line of the comments is always "ΑΡ. ΑΠΟΦΑΣΗΣ / ΕΤΟΣ: <decision>".
// Anything the user typed below it is kept; the line is dropped when the decision is cleared.
const withDecisionLine = (comments: string, decision: string) => {
    const lines = (comments ?? '').split('\n');
    const rest = lines[0].startsWith(DECISION_PREFIX) ? lines.slice(1) : lines;
    const restText = rest.join('\n');
    if (!decision.trim()) return restText;
    return restText ? `${DECISION_PREFIX}${decision}\n${restText}` : `${DECISION_PREFIX}${decision}`;
};

/** Β. Στοιχεία Οφειλής: amount, year, decision, comments + repeatable ΚΑΕ rows. */
const DebtSection = ({
                         form, errors, disabled, kaeOptions, setField,
                         onAddKae, onRemoveKae, onUpdateKae, onTotalBlur
                     }: Props) => {
    // running total shown next to the ΚΑΕ header
    const kaeSum = useMemo(() => sumKae(form.kae_rows), [form.kae_rows]);

    return (
        <CustomFormSection theme={"default"}>
            <h3 className="vf-section-title">Β. Στοιχεία Οφειλής</h3>
            <div className="row gy-4">
                <div className="col-12 col-md-4">
                    <TextField placeholder={AMOUNT_PLACEHOLDER} label="ΣΥΝΟΛΙΚΟ ΠΟΣΟ ( € )" required value={form.total_amount} disabled={disabled}
                               inputMode="decimal" error={errors.total_amount}
                               onChange={v => setField('total_amount', amountChars(v))}
                               onBlur={disabled ? undefined : onTotalBlur}/>
                </div>
                <div className="col-12 col-md-4">
                    <TextField label="ΟΙΚΟΝΟΜΙΚΟ ΕΤΟΣ" required value={form.financial_year} disabled={disabled}
                               inputMode="numeric" maxLength={4} error={errors.financial_year}
                               onChange={v => setField('financial_year', digitsOnly(v))}/>
                </div>
                <div className="col-12 col-md-4">
                    <TextField label="ΑΡ. ΑΠΟΦΑΣΗΣ / ΕΤΟΣ" required value={form.decision_number} disabled={disabled}
                               placeholder="π.χ. 11/2026" error={errors.decision_number}
                               onChange={v => {
                                   setField('decision_number', v);
                                   setField('comments', withDecisionLine(form.comments, v));
                               }}/>
                </div>
                <div className="col-12 col-md-8">
                    <TextField label="ΣΧΟΛΙΑ / ΑΙΤΙΟΛΟΓΙΑ" required multiline value={form.comments} disabled={disabled}
                               hint="Απαιτείται έτος και αριθμός απόφασης και στα σχόλια"
                               error={errors.comments} onChange={v => setField('comments', v)}/>
                </div>
            </div>


            <div className="vf-subhead">
                <div className="kae-heading">
                    <strong>{`ΓΡΑΜΜΕΣ ΚΑΕ `}</strong>
                    <span className="vf-hint">{` Άθροισμα: `} {money.format(kaeSum)}€</span>
                </div>
                {!disabled &&
                    <button type="button" className="vf-btn vf-btn--dark" onClick={onAddKae}>+ ΠΡΟΣΘΗΚΗ ΚΑΕ</button>}
            </div>
            {errors.kae_sum && <p className="error-message">{errors.kae_sum}</p>}

            {/* at least one ΚΑΕ row is required, so the last one can't be deleted */}
            {form.kae_rows.map(r => (
                <div className="row gy-3 vf-row" key={r.id}>
                    <div className="col-12 col-md-6">
                        <SelectField label="ΚΑΕ" required value={r.kae} disabled={disabled} options={kaeOptions}
                                     error={errors[errKey.kae(r.id, 'kae')]}
                                     onChange={v => onUpdateKae(r.id, {kae: v})}/>
                    </div>
                    <div className="col-12 col-md-4">
                        <TextField placeholder={AMOUNT_PLACEHOLDER} label="ΠΟΣΟ (€)" required value={r.amount} disabled={disabled} inputMode="decimal"
                                   error={errors[errKey.kae(r.id, 'amount')]}
                                   onChange={v => onUpdateKae(r.id, {amount: amountChars(v)})}/>
                    </div>
                    {!disabled && form.kae_rows.length > 1 && <DeleteRowButton onClick={() => onRemoveKae(r.id)}/>}
                </div>
            ))}
        </CustomFormSection>
    );
};

export default DebtSection;
