import React, {useCallback, useEffect, useState} from 'react';
import "./vevaiosi-single.scss";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import View from "./View";
import PageSubtitle from "../../../../components/UI/Typography/PageSubtitle";
import useSetBreadCrumbs from "../../../../context/useSetBreadcrumbs";
import {
    canEdit, statusUiType, StoredVevaiosiFile, Vevaiosi, VevaiosiFile, VevaiosiLookups, VevaiosiPayload
} from "../../../../models/Ked/Vevaiosi";
import {toastError, toastSuccess} from "../../../../services/toaster";
import {
    downloadVevaiosiFile, getSingleVevaiosi, getVevaiosiFormLookups, saveVevaiosi, syncVevaiosiFiles
} from "../../../../API/ked";
import {NewVevaiosiFile, SaveResult} from "./vevaiosiForm";
import PageTitle from "../../../../components/UI/Typography/PageTitle";

// the stored files of the form, as the backend returned them (local previews have no uuid and never reach here)
const storedFiles = (files: VevaiosiFile[]): StoredVevaiosiFile[] =>
    files.filter(f => f.uuid).map(f => ({uuid: f.uuid!, title: f.title, name: f.name, size: f.size}));

/**
 * Container for creating / viewing a single Βεβαίωση Οφειλής.
 * Loads lookups (+ the record when editing), decides read-only state, and owns every API call:
 * save, send to ΚΕΔ, and the immediate file add / delete used once the record has an id.
 * Presentation lives in <View>.
 */
const VevaiosiSingle = () => {
    const {single} = useParams();
    const navigate = useNavigate();
    const location = useLocation();
    const isNew = !single;

    // an existing record is "Προβολή Βεβαίωσης"; the payment page adds "Προβολή Είσπραξης" below it
    useSetBreadCrumbs(3, isNew ? 'Νέα Βεβαίωση Οφειλής' : 'Προβολή Βεβαίωσης');

    const [vevaiosi, setVevaiosi] = useState<Vevaiosi>();
    const [lookups, setLookups] = useState<VevaiosiLookups | null>(null);
    // id of the persisted record; null until the first successful save of a new one
    const [savedId, setSavedId] = useState<number | null>(single ? Number(single) : null);
    // set when an initial fetch fails, so we can show an error state instead of a blank page
    const [loadError, setLoadError] = useState<string | null>(null);

    // Return to the list, keeping its query string (filters / pagination).
    const goBack = useCallback(
        () => navigate({pathname: '..', search: location.search}),
        [navigate, location.search]
    );

    // Initial load: lookups always, the record only when editing.
    // Both requests run in parallel; `cancelled` guards against setting state after unmount / id change.
    useEffect(() => {
        let cancelled = false;
        setLoadError(null);

        getVevaiosiFormLookups()
            .then(res => { if (!cancelled) setLookups(res.data); })
            .catch(() => {
                if (cancelled) return;
                setLoadError('Δεν ήταν δυνατή η φόρτωση των λιστών.');
                toastError('Δεν ήταν δυνατή η φόρτωση των λιστών.');
            });

        if (single) {
            getSingleVevaiosi(single)
                .then(res => { if (!cancelled) setVevaiosi(res.data); })
                .catch(() => {
                    if (cancelled) return;
                    setLoadError('Δεν ήταν δυνατή η φόρτωση της βεβαίωσης.');
                    toastError('Δεν ήταν δυνατή η φόρτωση της βεβαίωσης.');
                });
        }

        return () => { cancelled = true; };
    }, [single]);

    // Drafts and rejected records are editable; anything else (or an unknown status) is view-only.
    const readOnly = !isNew && !!vevaiosi && !canEdit(vevaiosi);

    // Create or update the record. Local files are sent only on the create call;
    // once the record has an id, files are managed through syncVevaiosiFiles.
    const persist = useCallback(async (payload: VevaiosiPayload, newFiles: NewVevaiosiFile[]) => {
        const isCreate = savedId === null;
        const files = isCreate && newFiles.length ? newFiles : undefined;
        const res = await saveVevaiosi(payload, savedId, files);
        setSavedId(res.data.id);
        return {id: res.data.id as number, createdWithFiles: !!files};
    }, [savedId]);

    const handleSave = useCallback(async (payload: VevaiosiPayload, newFiles: NewVevaiosiFile[]): Promise<SaveResult> => {
        let result: { id: number; createdWithFiles: boolean };
        try {
            result = await persist(payload, newFiles);
        } catch {
            toastError('Κάτι πήγε στραβά κατά την αποθήκευση.');
            return {ok: false};
        }
        toastSuccess('Η βεβαίωση αποθηκεύτηκε ως πρόχειρο.');

        // The files just went up with the create call. Reload them so the form gets their uuids;
        // without them later file requests can't reference them. Skipped when no files were sent.
        if (result.createdWithFiles) {
            try {
                const res = await getSingleVevaiosi(String(result.id));
                return {ok: true, files: res.data.attachments ?? []};
            } catch {
                toastError('Η βεβαίωση αποθηκεύτηκε, αλλά δεν ήταν δυνατή η ανανέωση των αρχείων. Ανανεώστε τη σελίδα.');
            }
        }
        return {ok: true};
    }, [persist]);

    // Pulls a readable reason out of the backend error response, or null if there isn't one.
    const apiErrorMessage = (e: unknown): string | null => {
        const errors = (e as any)?.response?.data?.errors;
        if (typeof errors === 'string') return errors;
        if (Array.isArray(errors)) return errors.join(', ');
        if (errors && typeof errors === 'object') return Object.values(errors).flat().join(', ');
        return null;
    };

    // Same route as save, with submit: true; the backend saves and sends in one request.
    // Local files only go along when the record doesn't exist yet (same rule as save).
    const handleSend = useCallback(async (payload: VevaiosiPayload, newFiles: NewVevaiosiFile[]): Promise<boolean> => {
        const files = savedId === null && newFiles.length ? newFiles : undefined;
        try {
            await saveVevaiosi(payload, savedId, files, true);
            toastSuccess('Η βεβαίωση στάλθηκε στο ΚΕΔ.');
            goBack();
            return true;
        } catch (e) {
            const reason = apiErrorMessage(e);
            toastError(reason
                ? `Κάτι πήγε στραβά κατά την αποστολή: ${reason}`
                : 'Κάτι πήγε στραβά κατά την αποστολή.');
            return false;
        }
    }, [savedId, goBack]);

    // Saved record only: {existing: all stored files, new: the one being added}.
    // Resolves to the updated stored list, or null on failure.
    const handleUploadFile = useCallback(async (
        current: VevaiosiFile[], title: string, file: File
    ): Promise<StoredVevaiosiFile[] | null> => {
        if (savedId === null) return null;
        try {
            const res = await syncVevaiosiFiles(savedId, {
                existing: storedFiles(current),
                new: {title, name: file.name, size: file.size, file},
            });
            toastSuccess('Το αρχείο προστέθηκε.');
            return res.data;
        } catch {
            toastError('Κάτι πήγε στραβά κατά τη μεταφόρτωση του αρχείου.');
            return null;
        }
    }, [savedId]);

    // Saved record only: {existing: every stored file, including the one being removed, delete: that file}.
    // Resolves to the updated stored list, or null on failure.
    const handleDeleteFile = useCallback(async (
        current: VevaiosiFile[], uuid: string
    ): Promise<StoredVevaiosiFile[] | null> => {
        if (savedId === null) return null;
        const refs = storedFiles(current);
        const target = refs.find(r => r.uuid === uuid);
        if (!target) {
            toastError('Το αρχείο δεν βρέθηκε. Ανανεώστε τη σελίδα και δοκιμάστε ξανά.');
            return null;
        }
        try {
            const res = await syncVevaiosiFiles(savedId, {
                existing: refs,
                delete: target,
            });
            toastSuccess('Το αρχείο διαγράφηκε.');
            return res.data;
        } catch {
            toastError('Κάτι πήγε στραβά κατά τη διαγραφή του αρχείου.');
            return null;
        }
    }, [savedId]);

    // Saved record only: the content of one stored file, by uuid. Resolves to null on failure.
    const handleDownloadFile = useCallback(async (uuid: string): Promise<Blob | null> => {
        if (savedId === null) return null;
        try {
            const res = await downloadVevaiosiFile(savedId, uuid);
            return res.data;
        } catch {
            toastError('Κάτι πήγε στραβά κατά τη λήψη του αρχείου.');
            return null;
        }
    }, [savedId]);

    // Render the form only once everything it needs has arrived.
    const ready = !loadError && !!lookups && (isNew || !!vevaiosi);

    return (
        <div id='vevaiosi-view' className='vevaiosi-view-container'>
            {readOnly && vevaiosi && !loadError
                // sent / certified: status badge, decision number, protocol (the read-only design)
                ? <div className='mb-4'>
                    <span className={`vevaiosi-status vevaiosi-status--${statusUiType(vevaiosi.status) ?? 'default'}`}>
                        {vevaiosi.statusLabel}
                    </span>
                    <PageTitle>Βεβαίωση {vevaiosi.apofNoEtos ?? ''}</PageTitle>
                    {vevaiosi.auditProtocol &&
                        <p className='vevaiosi-page-desc'>{vevaiosi.auditProtocol}</p>}
                </div>
                : <div className='mb-4'>
                    <PageSubtitle>{isNew ? 'Νέα Βεβαίωση Οφειλής' : 'Βεβαίωση Οφειλής'}</PageSubtitle>
                    {!loadError && vevaiosi?.errorDescr &&
                        <p className='vevaiosi-page-desc text-danger'>
                            Αιτία απόρριψης: {vevaiosi.errorDescr}
                        </p>
                    }
                    {!loadError &&
                        <p className='vevaiosi-page-desc'>
                            Συμπληρώστε τα στοιχεία της οφειλής για να δημιουργήσετε και να υποβάλετε νέα βεβαίωση.
                        </p>
                    }
                </div>}

            {/* Error state: without this a failed fetch leaves an empty page with no way out */}
            {loadError &&
                <div className='vevaiosi-load-error'>
                    <p>{loadError}</p>
                    <button type='button' className='btn btn-outline-secondary' onClick={goBack}>
                        Επιστροφή στη λίστα
                    </button>
                </div>
            }

            {ready &&
                <View
                    key={single ?? 'new'}
                    details={vevaiosi}
                    lookups={lookups!}
                    savedId={savedId}
                    readOnly={readOnly}
                    onSave={handleSave}
                    onSend={handleSend}
                    onUploadFile={handleUploadFile}
                    onDeleteFile={handleDeleteFile}
                    onDownloadFile={handleDownloadFile}
                    onBack={goBack}
                />
            }
        </div>
    );
};

export default VevaiosiSingle;
