import React, {useEffect, useMemo, useState} from 'react';
import FormButtonsContainer from "../../../../components/UI/Forms/FormButton/FormButtonsContainer";
import FormButtonBack from "../../../../components/UI/Forms/FormButton/FormButtonBack";
import FormButtonCancel from "../../../../components/UI/Forms/FormButton/FormButtonCancel";
import FormButtonSubmit from "../../../../components/UI/Forms/FormButton/FormButtonSubmit";
import FormButtonSave from "../../../../components/UI/Forms/FormButton/FormButtonSave";
import ConfirmationModal from "../../../../components/UI/Modal/ActionsModal/ConfirmationModal";
import {
    Codebtor, KaeRow, StoredVevaiosiFile, Vevaiosi, VevaiosiFile, VevaiosiLookups, VevaiosiPayload
} from "../../../../models/Ked/Vevaiosi";
import {toastError} from "../../../../services/toaster";
import {
    emptyCodebtor, emptyKae, errKey, Errors, FormState, NewVevaiosiFile, newFilesOf, requiredFilled, SaveResult,
    SetField, syncDecisionInComments, toFormFiles, toFormState, toPayload, uid, validate
} from "./vevaiosiForm";
import DebtorSection from "./DebtorSection";
import DebtSection from "./DebtSection";
import FilesSection from "./FilesSection";
import SignatorySection from "./SignatorySection";
import {ReadOnlySummary} from "./ReadOnlySummary";

interface ViewProps {
    details?: Vevaiosi
    lookups: VevaiosiLookups
    // id of the persisted record, null until the first save. Decides how files are handled:
    // null -> files stay local and go with the save/send request; set -> immediate file requests.
    savedId: number | null
    readOnly: boolean
    onSave: (payload: VevaiosiPayload, newFiles: NewVevaiosiFile[]) => Promise<SaveResult>
    onSend: (payload: VevaiosiPayload, newFiles: NewVevaiosiFile[]) => Promise<boolean>
    // only called when savedId is set; get the current files (the request carries the full list)
    // and resolve to the updated stored list, or null on failure
    onUploadFile: (current: VevaiosiFile[], title: string, file: File) => Promise<StoredVevaiosiFile[] | null>
    onDeleteFile: (current: VevaiosiFile[], uuid: string) => Promise<StoredVevaiosiFile[] | null>
    // a stored file's content, or null on failure
    onDownloadFile: (uuid: string) => Promise<Blob | null>
    onBack: () => void
}

const PENDING_FILE_MSG = 'Έχετε επιλέξει αρχείο που δεν έχει προστεθεί. Συμπληρώστε τίτλο και πατήστε ΠΡΟΣΘΗΚΗ, ή αφαιρέστε την επιλογή.';

// What the form would save, as a comparable string. Built from the payload (not the raw form state)
// because the form state carries random row ids that change on every load.
const snapshot = (f: FormState) => JSON.stringify(toPayload(f));

// a ΚΑΕ row with nothing picked yet (the select uses '' for "no value")
const kaeEmpty = (r: KaeRow) => r.kae === '' || r.kae == null;

/**
 * Βεβαίωση Οφειλής form. Owns the form state, errors, and the save / send / cancel flow.
 * Each section only renders and reports changes; validation rules live in vevaiosiForm.ts.
 * The parent remounts this component (via `key`) when the record changes, so initial state
 * from `details` is read only once.
 */
const View = ({
                  details, lookups, savedId, readOnly, onSave, onSend, onUploadFile, onDeleteFile, onDownloadFile, onBack
              }: ViewProps) => {
    const [form, setForm] = useState<FormState>(() => toFormState(details));
    const [errors, setErrors] = useState<Errors>({});
    // the last saved values (the loaded record, or what the last successful save sent)
    const [baseline, setBaseline] = useState(() => snapshot(form));
    // true only when the form differs from the saved values; editing a field and putting
    // the old value back counts as unchanged. Files on a saved record sync immediately, so they never count.
    const dirty = useMemo(() => snapshot(form) !== baseline, [form, baseline]);
    const [busy, setBusy] = useState(false);
    const [modal, setModal] = useState<'cancel' | 'send' | null>(null);
    // a file was picked in section Γ but not added yet; blocks save/send so it isn't lost silently
    const [hasPendingFile, setHasPendingFile] = useState(false);
    // an immediate file request is in flight; save/send and other file actions wait for it
    const [fileBusy, setFileBusy] = useState(false);

    const isPersisted = savedId !== null;

    // the ΚΑΕ to preselect: only when the lookups offer exactly one, since then there is no choice to make
    const onlyKae = useMemo<number | null>(
        () => (lookups.kae.length === 1 ? Number(lookups.kae[0].value) : null),
        [lookups.kae]
    );

    // New record only: fill empty ΚΑΕ rows with the single option. An effect (not the useState initializer)
    // so it also works if the lookups arrive after mount. A loaded record is never touched,
    // so it can't turn dirty just by opening it.
    useEffect(() => {
        if (details || onlyKae === null) return;
        setForm(f => f.kae_rows.some(kaeEmpty)
            ? {...f, kae_rows: f.kae_rows.map(r => (kaeEmpty(r) ? {...r, kae: onlyKae} : r))}
            : f);
    }, [details, onlyKae]);

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

    // every user edit goes through here (`dirty` is derived from the form, so nothing else to track)
    const change = (fn: (f: FormState) => FormState) => setForm(fn);

    // drop errors as soon as the related field is edited; no-op (same object) if none exist
    const clearErrors = (...keys: string[]) =>
        setErrors(prev => {
            if (!keys.some(k => k in prev)) return prev;
            const next = {...prev};
            keys.forEach(k => delete next[k]);
            return next;
        });

    const setField: SetField = (key, value) => {
        if (key === 'decision_number') {
            // mirror the decision number/year into the comments ("11/2026 - ") as the user types it;
            // computed from the previous state, so the old value is always the one to replace
            const next = value as string;
            change(f => ({
                ...f,
                decision_number: next,
                comments: syncDecisionInComments(f.comments, f.decision_number, next),
            }));
        } else {
            change(f => ({...f, [key]: value}));
        }
        clearErrors(key as string);
        // cross-field rules: these fields also affect other errors
        if (key === 'total_amount') clearErrors('kae_sum');
        if (key === 'decision_number') clearErrors('comments');
    };

    /* ------------------------------- co-obligors ------------------------------- */

    const addCodebtor = () => change(f => ({...f, codebtors: [...f.codebtors, emptyCodebtor()]}));
    const removeCodebtor = (id: string) => {
        change(f => ({...f, codebtors: f.codebtors.filter(c => c.id !== id)}));
        clearErrors(...['afm', 'name', 'relation'].map(k => errKey.codebtor(id, k)));
    };
    const updateCodebtor = (id: string, patch: Partial<Codebtor>) => {
        change(f => ({...f, codebtors: f.codebtors.map(c => (c.id === id ? {...c, ...patch} : c))}));
        clearErrors(...Object.keys(patch).map(k => errKey.codebtor(id, k)));
    };

    /* --------------------------------- KAE rows -------------------------------- */

    // a new row starts with the single ΚΑΕ already picked, when there is only one
    const addKae = () => change(f => {
        const row = emptyKae();
        return {...f, kae_rows: [...f.kae_rows, onlyKae !== null && kaeEmpty(row) ? {...row, kae: onlyKae} : row]};
    });
    const removeKae = (id: string) => {
        change(f => ({...f, kae_rows: f.kae_rows.filter(r => r.id !== id)}));
        // removing a row changes the sum, so a stale sum error must go too
        clearErrors('kae_sum', errKey.kae(id, 'kae'), errKey.kae(id, 'amount'));
    };
    const updateKae = (id: string, patch: Partial<KaeRow>) => {
        change(f => ({...f, kae_rows: f.kae_rows.map(r => (r.id === id ? {...r, ...patch} : r))}));
        clearErrors('kae_sum', ...Object.keys(patch).map(k => errKey.kae(id, k)));
    };

    // Focus left the total amount: with a single ΚΑΕ row, its amount follows the total
    // (always overwritten, so correcting the total corrects the row too).
    // With several rows there is no way to know how to split it, so nothing changes.
    const handleTotalBlur = () => {
        const total = form.total_amount.trim();
        if (!total || form.kae_rows.length !== 1) return;
        const row = form.kae_rows[0];
        if (row.amount !== total) updateKae(row.id, {amount: total});
    };

    /* ---------------------------------- files ---------------------------------- */

    // New record: keep the file in the form (preview only); it is sent with the next save/send.
    // Saved record: send the full list right away and replace the files with what the server returns.
    // Server-side changes don't make the form dirty, because there is nothing left to lose for them.
    const addFile = async (title: string, file: File): Promise<boolean> => {
        if (!isPersisted) {
            change(f => ({...f, files: [...f.files, {id: uid(), title, name: file.name, size: file.size, file}]}));
            return true;
        }
        setFileBusy(true);
        const updated = await onUploadFile(form.files, title, file);
        setFileBusy(false);
        if (!updated) return false;
        setForm(f => ({...f, files: toFormFiles(updated)}));
        return true;
    };

    // New record: just drop it from the preview. Saved record: send the full list with this one flagged.
    const removeFile = async (file: VevaiosiFile): Promise<void> => {
        if (!isPersisted) {
            change(f => ({...f, files: f.files.filter(x => x.id !== file.id)}));
            return;
        }
        if (!file.uuid) {
            // the record returns attachments as {title, filepath}, with no uuid to delete them by
            toastError('Το αρχείο δεν μπορεί να διαγραφεί ακόμα.');
            return;
        }
        setFileBusy(true);
        const updated = await onDeleteFile(form.files, file.uuid);
        setFileBusy(false);
        if (updated) setForm(f => ({...f, files: toFormFiles(updated)}));
    };
    const handlePendingChange = (pending: boolean) => {
        setHasPendingFile(pending);
        if (!pending) clearErrors('pending_file');
    };

    /* --------------------------------- actions --------------------------------- */

    // validates, shows errors, and scrolls to the first one; returns true when the form is valid
    const runValidation = (): boolean => {
        const e = validate(form);
        if (hasPendingFile) e.pending_file = PENDING_FILE_MSG;
        setErrors(e);
        if (Object.keys(e).length === 0) return true;
        toastError('Υπάρχουν πεδία που χρειάζονται διόρθωση.');
        // wait one frame so the new error messages are in the DOM
        requestAnimationFrame(() =>
            document.querySelector('.vevaiosi-form .error-message')?.scrollIntoView({behavior: 'smooth', block: 'center'}));
        return false;
    };

    // Local files (only exist before the first save) travel with the request; for a saved record
    // newFilesOf() is empty, because every file there already has a uuid.
    const handleSaveClick = async () => {
        if (busy || fileBusy || saveDisabledUnchanged || missingRequired || !runValidation()) return;
        setBusy(true);
        const payload = toPayload(form);
        const res = await onSave(payload, newFilesOf(form));
        setBusy(false);
        if (!res.ok) return;
        // what was just saved becomes the new baseline, so ΑΠΟΘΗΚΕΥΣΗ disables again until the next edit
        setBaseline(JSON.stringify(payload));
        // the save just created the record with its files: swap the local previews for the
        // server copies, so later file requests have their uuids
        if (res.files) setForm(f => ({...f, files: toFormFiles(res.files!)}));
    };

    // validate first, then ask for confirmation; the actual send happens in confirmSend
    const handleSendClick = () => {
        if (busy || fileBusy || missingRequired || !runValidation()) return;
        setModal('send');
    };

    const confirmSend = async () => {
        setBusy(true);
        const ok = await onSend(toPayload(form), newFilesOf(form));
        // on success the parent navigates away, so only reset on failure
        setBusy(false);
        if (!ok) setModal(null);
    };

    // Saved record (or read-only): "Πίσω". New record: "Ακύρωση" (always with confirmation).
    const showBack = readOnly || isPersisted;

    // A saved record has nothing to save until a field changes.
    const saveDisabledUnchanged = isPersisted && !dirty;
    // A new (not yet saved) record can't be saved or sent until every required field has a value.
    const missingRequired = useMemo(() => !isPersisted && !requiredFilled(form), [isPersisted, form]);

    // "Πίσω" leaves directly, unless a saved record has unsaved edits; then it confirms first
    const handleBackClick = () => {
        if (!readOnly && dirty) setModal('cancel');
        else onBack();
    };

    // files can be added / removed in every status, so this section ignores readOnly
    const filesSection = (
        <FilesSection
            title={readOnly ? 'Προσθήκη αρχείων' : undefined}
            files={form.files} disabled={false} busy={busy || fileBusy} error={errors.pending_file}
            onAdd={addFile} onRemove={removeFile} onDownload={f => onDownloadFile(f.uuid!)}
            onPendingChange={handlePendingChange}
        />
    );

    return (
        <div id="view" className="vevaiosi-form">
            {readOnly && details
                // sent / certified: summary card (signer and ΕΛΕΓΧΟΣ ΠΛΗΡΩΜΩΝ included), then files
                ? <>
                    <ReadOnlySummary details={details} signatories={lookups.signatories}/>
                    {filesSection}
                </>
                // draft / rejected / new: the editable form
                : <>
                    <DebtorSection
                        form={form} errors={errors} disabled={readOnly} relations={lookups.relations}
                        setField={setField}
                        onAddCodebtor={addCodebtor} onRemoveCodebtor={removeCodebtor} onUpdateCodebtor={updateCodebtor}
                    />

                    <DebtSection
                        form={form} errors={errors} disabled={readOnly} kaeOptions={lookups.kae}
                        setField={setField}
                        onAddKae={addKae} onRemoveKae={removeKae} onUpdateKae={updateKae}
                        onTotalBlur={handleTotalBlur}
                    />

                    {filesSection}

                    <SignatorySection
                        value={form.signatory_id} options={lookups.signatories} error={errors.signatory_id}
                        disabled={readOnly} onChange={v => setField('signatory_id', v)}
                    />
                </>}

            <div className="vf-actions">
                <FormButtonsContainer align={'right'}>
                    {showBack
                        ? <FormButtonBack buttonType={'button'} disabled={busy} onClick={handleBackClick}>ΠΙΣΩ</FormButtonBack>
                        : <FormButtonCancel buttonType={'button'} disabled={busy} onClick={() => setModal('cancel')}>
                            <p>ΑΚΥΡΩΣΗ</p>
                        </FormButtonCancel>}
                    {!readOnly && <>
                        <FormButtonSave buttonType={'button'}
                                        disabled={busy || fileBusy || saveDisabledUnchanged || missingRequired}
                                        onClick={handleSaveClick}>
                            ΑΠΟΘΗΚΕΥΣΗ
                        </FormButtonSave>
                        <FormButtonSubmit buttonType={'button'}
                                          disabled={busy || fileBusy || missingRequired}
                                          onClick={handleSendClick}>
                            ΑΠΟΣΤΟΛΗ ΣΤΟ ΚΕΔ
                        </FormButtonSubmit>
                    </>}
                </FormButtonsContainer>
            </div>

            {modal === 'cancel' &&
                <ConfirmationModal
                    FormButtonCancelText={'ΟΧΙ'}
                    FormButtonSubmitText={'ΝΑΙ, ΑΚΥΡΩΣΗ'}
                    onClose={() => setModal(null)}
                    title={''}
                    text={''}
                    modalAction={onBack}
                    className={'vevaiosi-cancel-modal'}>
                    <p className='text-center mb-5'>
                        Ό,τι έχετε συμπληρώσει και δεν έχει αποθηκευτεί <b>θα χαθεί</b>.<br/>
                        Θέλετε να συνεχίσετε;
                    </p>
                </ConfirmationModal>}

            {modal === 'send' &&
                <ConfirmationModal
                    FormButtonCancelText={'ΑΚΥΡΩΣΗ'}
                    FormButtonSubmitText={'ΑΠΟΣΤΟΛΗ'}
                    // can't close while the request is in flight
                    onClose={() => !busy && setModal(null)}
                    title={''}
                    text={''}
                    loading={busy}
                    isDisabled={busy}
                    modalAction={confirmSend}
                    className={'vevaiosi-send-modal'}>
                    <p className='text-center mb-5'>
                        Η βεβαίωση θα αποσταλεί στο <b>ΚΕΔ</b> και δεν θα μπορεί να τροποποιηθεί.<br/>
                        Θέλετε να συνεχίσετε;
                    </p>
                </ConfirmationModal>}
        </div>
    );
};

export default View;
