import React, {useRef, useState} from 'react';
import CustomFormSection from "../../../../components/UI/Forms/CustomFormSection/CustomFormSection";
import CustomLabel from "../../../../components/UI/Forms/CustomLabel/CustomLabel";
import {VevaiosiFile} from "../../../../models/Ked/Vevaiosi";
import {toastError} from "../../../../services/toaster";
import {DownloadIcon, TextField, TrashIcon} from "./fields";
import {ALLOWED_EXT, extOf, MAX_FILE_SIZE} from "./vevaiosiForm";

interface Props {
    // the read-only page shows the section without its letter
    title?: string
    files: VevaiosiFile[]
    disabled: boolean
    // a file upload / delete is in flight (disables the controls)
    busy: boolean
    // validation error when a file was picked but never added (set by View on save/send)
    error?: string
    // resolves true when the file was added (locally or on the server); inputs reset only then
    onAdd: (title: string, file: File) => Promise<boolean>
    onRemove: (file: VevaiosiFile) => Promise<void>
    // a stored file (has a uuid, no File object): resolves to its content, or null on failure
    onDownload: (file: VevaiosiFile) => Promise<Blob | null>
    // tells View whether a picked-but-not-added file exists, so save/send can block on it
    onPendingChange: (pending: boolean) => void
}

// Hint and error text derive from the constants, so changing the rules in vevaiosiForm.ts
// never leaves the UI saying something else.
const MAX_MB = Math.round(MAX_FILE_SIZE / (1024 * 1024));
const ALLOWED_LABEL = ALLOWED_EXT.map(x => '.' + x).join(', ');

// icon modifier per extension; anything unexpected falls back to the generic style
const ICON_TYPES = ['pdf', 'zip', 'xlsx', 'docx', 'jpg'];
const iconClass = (ext: string) => `vf-file-icon--${ICON_TYPES.includes(ext) ? ext : 'other'}`;

// hands a File / Blob to the browser as a download named `name`
const saveAs = (blob: Blob, name: string) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    a.click();
    // revoking synchronously can cancel the download in Safari/Firefox
    setTimeout(() => URL.revokeObjectURL(url), 0);
};

/**
 * Γ. Προσθήκη αρχείων (optional). Owns the "pick a file + give it a title" state.
 * Whether add/remove is local (new record) or an immediate backend call (saved record)
 * is decided by View; this section just awaits onAdd / onRemove.
 */
const FilesSection = ({
                          title = 'Γ. Προσθήκη αρχείων', files, disabled, busy, error, onAdd, onRemove, onDownload, onPendingChange
                      }: Props) => {
    const [fileTitle, setFileTitle] = useState('');
    const [pendingFile, setPendingFile] = useState<File | null>(null);
    const [fileError, setFileError] = useState('');
    const [uploading, setUploading] = useState(false);
    const [removingId, setRemovingId] = useState<string | null>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);

    // single place that changes pendingFile, so View always knows about it
    const setPending = (file: File | null) => {
        setPendingFile(file);
        onPendingChange(!!file);
        if (!file && fileInputRef.current) fileInputRef.current.value = '';
    };

    const handlePickedFile = (file?: File | null) => {
        if (!file || busy) return;
        if (!ALLOWED_EXT.includes(extOf(file.name))) return setFileError('Μη επιτρεπόμενος τύπος αρχείου.');
        if (file.size > MAX_FILE_SIZE) return setFileError(`Το αρχείο υπερβαίνει τα ${MAX_MB}MB.`);
        setFileError('');
        setPending(file);
    };

    // on failure the picked file and title stay, so the user can retry
    const addFile = async () => {
        if (!pendingFile || !fileTitle.trim() || busy) return;
        setUploading(true);
        const ok = await onAdd(fileTitle.trim(), pendingFile);
        setUploading(false);
        if (!ok) return;
        setFileTitle('');
        setPending(null);
    };

    // a picked file is still in the browser; a stored one is fetched by uuid
    const downloadFile = async (f: VevaiosiFile) => {
        if (f.file) return saveAs(f.file, f.name);
        if (!f.uuid) {
            toastError('Το αρχείο δεν είναι διαθέσιμο για λήψη.');
            return;
        }
        const blob = await onDownload(f);
        if (blob) saveAs(blob, f.name);
    };

    const removeFile = async (f: VevaiosiFile) => {
        if (busy) return;
        setRemovingId(f.id);
        await onRemove(f);
        setRemovingId(null);
    };

    return (
        <CustomFormSection theme={"default"}>
            <h3 className="vf-section-title">{title}</h3>

            {!disabled &&
                <div className="row gy-3 align-items-start vf-file-row">
                    <div className="col-12 col-md-5">
                        <TextField label="ΤΙΤΛΟΣ ΑΡΧΕΙΟΥ" value={fileTitle} disabled={uploading}
                                   placeholder="Παρακαλώ συμπληρώστε τίτλο αρχείου"
                                   onChange={setFileTitle}/>
                    </div>
                    <div className="col-12 col-md-5">
                        <div className="vf-field">
                            <CustomLabel>ΠΡΟΣΘΗΚΗ ΑΡΧΕΙΟΥ</CustomLabel>
                            <label className={`vf-dropzone ${pendingFile ? 'has-file' : ''}`}
                                   onDragOver={e => e.preventDefault()}
                                   onDrop={e => {
                                       e.preventDefault();
                                       handlePickedFile(e.dataTransfer.files?.[0]);
                                   }}>
                                <input ref={fileInputRef} type="file" hidden disabled={busy}
                                       accept={ALLOWED_EXT.map(x => '.' + x).join(',')}
                                       onChange={e => handlePickedFile(e.target.files?.[0])}/>
                                {pendingFile
                                    ? pendingFile.name
                                    : 'Πατήστε εδώ για να επιλέξετε αρχείο ή σύρετέ το εδώ'}
                            </label>
                            <span className="vf-hint">
                                Επιτρεπόμενα αρχεία: {ALLOWED_LABEL}. Μέγιστο μέγεθος {MAX_MB}MB
                                {/* lets the user drop a picked file instead of being forced to add it */}
                                {pendingFile && !uploading &&
                                    <button type="button" className="vf-link-btn" onClick={() => setPending(null)}>
                                        Αφαίρεση επιλογής
                                    </button>}
                            </span>
                            {fileError && <p className="error-message">{fileError}</p>}
                            {error && <p className="error-message">{error}</p>}
                        </div>
                    </div>
                    <div className="col-12 col-md-2 vevaiosi-file-add-button">
                        <div className="vf-field">
                            <CustomLabel>&nbsp;</CustomLabel>
                            <button type="button" className="vf-btn vf-btn--green vf-btn--lg"
                                    disabled={!pendingFile || !fileTitle.trim() || busy} onClick={addFile}>
                                {uploading ? 'ΜΕΤΑΦΟΡΤΩΣΗ...' : 'ΠΡΟΣΘΗΚΗ'}
                            </button>
                        </div>
                    </div>
                </div>}

            <hr className="vf-divider"/>

            {files.length === 0
                ? <p className="vf-empty">Δεν έχει προστεθεί αρχείο</p>
                : <>
                    <p className="vf-files-title">Επισυναπτόμενα αρχεία ({files.length})</p>
                    {files.map(f => {
                        const ext = extOf(f.name);
                        return (
                            <div className={`vf-file-item ${removingId === f.id ? 'is-removing' : ''}`} key={f.id}>
                                <span className={`vf-file-icon ${iconClass(ext)}`}>
                                    {ext.toUpperCase()}
                                </span>
                                <div className="vf-file-info">
                                    <b>{f.title}</b>
                                    <span>{f.name}</span>
                                </div>
                                <div className="vf-file-actions">
                                    <button type="button" className="vf-icon-btn" title="Λήψη"
                                            onClick={() => downloadFile(f)}><DownloadIcon/></button>
                                    {/* read-only (already sent) records can't lose files */}
                                    {!disabled &&
                                        <button type="button" className="vf-icon-btn" title="Διαγραφή"
                                                disabled={busy} onClick={() => removeFile(f)}><TrashIcon/></button>}
                                </div>
                            </div>
                        );
                    })}
                </>}
        </CustomFormSection>
    );
};

export default FilesSection;
