const formatBytes = (b) => {
    if (!b) return '';
    if (b < 1024)        return `${b} B`;
    if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
    return `${(b / (1024 * 1024)).toFixed(1)} MB`;
};

const fileIcon = (mime) => {
    if (!mime) return { cls: 'file', icon: 'fa-file' };
    if (mime.startsWith('image/'))                       return { cls: 'img',  icon: 'fa-file-image' };
    if (mime === 'application/pdf')                      return { cls: 'pdf',  icon: 'fa-file-pdf' };
    if (mime.includes('word') || mime.includes('odt'))   return { cls: 'doc',  icon: 'fa-file-word' };
    if (mime.includes('excel') || mime.includes('sheet'))return { cls: 'xls',  icon: 'fa-file-excel' };
    if (mime.includes('zip') || mime.includes('rar'))    return { cls: 'zip',  icon: 'fa-file-archive' };
    return { cls: 'file', icon: 'fa-file' };
};

const AttachmentsPanel = ({ entityType, entityId }) => {
    const [attachments, setAttachments] = React.useState([]);
    const [loading, setLoading]         = React.useState(true);
    const [uploading, setUploading]     = React.useState(false);
    const [dragOver, setDragOver]       = React.useState(false);
    const fileInputRef = React.useRef(null);

    const load = () => {
        api.getAttachments(entityType, entityId)
            .then(setAttachments)
            .catch(console.error)
            .finally(() => setLoading(false));
    };

    React.useEffect(() => { load(); }, [entityType, entityId]);

    const handleFiles = async (files) => {
        if (!files?.length) return;
        setUploading(true);
        try {
            for (const file of Array.from(files)) {
                await api.uploadAttachment(entityType, entityId, file);
            }
            load();
        } catch (err) {
            alert('Upload failed: ' + err.message);
        } finally {
            setUploading(false);
        }
    };

    const handleDelete = async (att) => {
        if (!window.confirm(`Delete "${att.original_name}"?`)) return;
        try { await api.deleteAttachment(att.id); load(); }
        catch (err) { alert(err.message); }
    };

    return (
        <div className="attachments-section">
            <h4>
                <span><i className="fas fa-paperclip" style={{ color: '#6b7280' }}></i> Files &amp; Attachments {attachments.length > 0 && `(${attachments.length})`}</span>
                <button className="btn btn-secondary btn-small" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
                    {uploading ? <><i className="fas fa-spinner fa-spin"></i> Uploading…</> : <><i className="fas fa-upload"></i> Upload</>}
                </button>
            </h4>

            {/* Drop zone */}
            <div
                className={`upload-zone ${dragOver ? 'drag-over' : ''}`}
                style={{ marginBottom: '0.75rem', padding: '0.875rem' }}
                onClick={() => fileInputRef.current?.click()}
                onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                onDragLeave={() => setDragOver(false)}
                onDrop={(e) => { e.preventDefault(); setDragOver(false); handleFiles(e.dataTransfer.files); }}
            >
                <input ref={fileInputRef} type="file" multiple onChange={e => handleFiles(e.target.files)} />
                <i className="fas fa-cloud-upload-alt" style={{ marginRight: '0.5rem' }}></i>
                Drop files here or click to browse &mdash; tax forms, photos, floorplans, docs (25 MB max)
            </div>

            {/* File list */}
            {loading ? (
                <div style={{ color: '#6b7280', fontSize: '0.875rem' }}><i className="fas fa-spinner fa-spin"></i> Loading…</div>
            ) : attachments.length === 0 ? (
                <p style={{ color: '#9ca3af', fontSize: '0.8125rem' }}>No files attached yet.</p>
            ) : attachments.map(att => {
                const { cls, icon } = fileIcon(att.mime_type);
                return (
                    <div key={att.id} className="attachment-item">
                        <div className={`attachment-icon ${cls}`}><i className={`fas ${icon}`}></i></div>
                        <div className="attachment-info">
                            <div className="attachment-name">{att.original_name}</div>
                            <div className="attachment-meta">{formatBytes(att.size_bytes)} · {formatDate(att.created_at)}{att.uploaded_by_name ? ` · ${att.uploaded_by_name}` : ''}</div>
                        </div>
                        <a href={`/api/attachments/${att.id}/download`} className="btn btn-secondary btn-small" title="Download" style={{ textDecoration: 'none' }}>
                            <i className="fas fa-download"></i>
                        </a>
                        <button className="btn-icon-sm danger" onClick={() => handleDelete(att)} title="Delete">
                            <i className="fas fa-trash"></i>
                        </button>
                    </div>
                );
            })}
        </div>
    );
};
